10

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

Type typeName = simObjects.getType();

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

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

但是这个方法返回一个字符串,我需要它在 System.Type 中,任何天才可以帮助我吗?

4

2 回答 2

5

我没有按照我的意愿使用反射,但它工作得很好。

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”,而在第二个循环中(假设条件为“Son”返回 true)、“age”和“name”。

于 2014-12-17T12:38:16.893 回答
1

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

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

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

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);
于 2014-09-10T18:24:39.763 回答