Convert COM object to .Net Object
public int Set(int newValue,Object obj)
{
//System.Windows.Forms.Control ctrl = (System.Windows.FormsControl)Object;
}
The Object here is COM object. Now I want to convert it to a .NET object a开发者_开发技巧nd get hold of its properties. What is the easiest way to do it?
You can't convert a COM object into a Windows.Forms.Control object directly. It isn't that specific type.
The COM object should, if you use the correct type library, provide you with properties of its own. You should be able to use its properties directly, provided you cast it to the appropriate type.
The fact that the object in question is a COM object is not a problem. You don't have to convert it to a .NET object because it already is one. You get hold of the properties on this object as you would any other .NET object for which you didn't have type information, for example:
var objectType = obj.GetType();
foreach(var prop in objectType.GetProperties())
{
Console.WriteLine("Property {0} of type {1}",
prop.Name, prop.PropertyType.Name);
}
To invoke a property you can use the InvokeMember method of the Type class. Here's how to set the "Visible" property (if it exists) on your object to true
:
objectType.InvokeMember("Visible", BindingFlags.SetProperty,
null, obj, new object[] { true });
If you're using .NET 4 or 4.5, you can use the dynamic keyword to make working with COM originated .NET objects easier:
var xlAppType = Type.GetTypeFromProgID("Excel.Application");
dynamic xlApp = Activator.CreateInstance(xlAppType);
xlApp.Visible = true;
Note how the invocation of the Visible property was incantation-free in that last example. I try to use dynamics whenever possible to work with COM objects these days.
精彩评论