问题描述
public int Set(int newValue,Object obj)
{
//System.Windows.Forms.Control ctrl = (System.Windows.FormsControl)Object;
}
此处的对象是COM对象。现在我想将其转换为.NET对象并获取其属性。最简单的方法是什么?
The Object here is COM object. Now I want to convert it to a .NET object and get hold of its properties. What is the easiest way to do it?
推荐答案
问题对象是一个COM对象的事实不是一个问题。您不必将其转换为.NET对象,因为它已经是一个。您可以获得此对象的属性,就像您没有类型信息的任何其他.NET对象一样。例如:
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);
}
要调用属性,您可以使用Type类的InvokeMember方法。以下是如何将对象上的Visible属性(如果存在)设置为 true
:
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 });
如果使用.NET 4或4.5,可以使用dynamic关键字COM起源.NET对象更容易:
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;
请注意在最后一个示例中Visible属性的调用是无。的。我尝试使用动态,尽可能地使用COM对象这些天。
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.
这篇关于将COM对象转换为.Net对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!