如何在C#中的System.Type中返回System .__ COMObject的类型

时间:2014-09-10 18:05:48

标签: c# reflection gettype comobject system.type

我正在做一个程序,我想做一个反射,但为此,我需要一个Type类型的对象,对吧?使用.GetProperties()方法...所以我尝试了这个:

Type typeName = simObjects.getType();

但.GetType()返回“System .__ COMObject”。这没有用。 .typeof()也是如此。我搜索并找到了另一个代码,这个代码:

Type typeName = (Type)Microsoft.VisualBasic.Information.TypeName(simObjects);

但是这个方法返回一个String,我需要它在System.Type中,任何天才请帮帮我吗?

2 个答案:

答案 0 :(得分:2)

嗯,我知道它是一个迟到的衣服,我不久前解决了我的问题,我会回复,希望它可以帮助别人。

我没有按照自己的意愿使用反射,但它的工作非常好。

foreach(PropertyDescriptor descrip in TypeDescriptor.GetProperties(COMObject))
{
    if(descrip.Name == "Attribute Name")
    {
        foreach(PropertyDescriptor descrip2 in TypeDescriptor.GetProperties(descrip))
        {
           if(descrip2.Name == "sub attribute Name")
           {
           }
        } 
    }
}

此代码返回属性的名称,例如,假设我的COMObject具有以下属性:

int age;
string name;
Son Phill;

和儿子:

int age;
string name;

在第一个循环中,descrip.Name将是“age”,“name”和“Phill”,而在第二个循环中(认为condiiton返回true并带有“Son”),“age”和“name”

希望这有助于某人。

答案 1 :(得分:0)

有关如何获取类型的信息,请参阅此链接:

http://support.microsoft.com/kb/320523

请参阅以下有关COM对象和反射的答案:

https://stackoverflow.com/a/10617479/4004002

另外,你知道这些属性是提前的吗?如果是这样,你可以(我从来没有尝试过COM对象)能够使用Dynamics来访问属性。

dynamic d = simObjects;
string myVariable = d.SomeProperty;

编辑:此链接说明使用动态和COM

http://msdn.microsoft.com/en-us/magazine/ff714583.aspx

如果它消失了:

public static class WordDocument
{
    public const String TemplateName = @"Sample.dotx";
    public const String CurrentDateBookmark = "CurrentDate";
    public const String SignatureBookmark = "Signature";

    public static void Create(string file, DateTime now, String author)
    {
         // Run Word and make it visible for demo purposes
         dynamic wordApp = new Application { Visible = true };

        // Create a new document
        var doc = wordApp.Documents.Add(TemplateName);
        templatedDocument.Activate();

        // Fill the bookmarks in the document
        doc.Bookmarks[CurrentDateBookmark].Range.Select();
        wordApp.Selection.TypeText(current.ToString());
        doc.Bookmarks[SignatureBookmark].Range.Select();
        wordApp.Selection.TypeText(author);