【问题标题】:How return the type of a System.__COMObject in System.Type in C#如何在 C# 中的 System.Type 中返回 System.__COMObject 的类型
【发布时间】:2014-11-04 12:00:03
【问题描述】:

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

Type typeName = simObjects.getType();

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

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

但是这个方法返回一个String,我在System.Type中需要它,有大神能帮帮我吗?

【问题讨论】:

标签: c# reflection gettype comobject system.type


【解决方案1】:

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

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” .

【讨论】:

    【解决方案2】:

    查看此链接了解如何获取类型:

    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);
    

    【讨论】:

    • 我看到了这个链接,没有帮助,这个例子只对 Excel 有帮助,我没有为 excel 做任何事情... =(
    • 只要您知道属性的名称,相同的技术可以应用于任何类型的对象。动态属性在运行时进行评估。只需将您的 COM 对象分配给一个动态对象并像访问任何 POCO 一样访问它的属性。
    • 我正在阅读此链接,我不确定是否会有所帮助,但无论如何谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 2016-03-17
    • 2016-02-02
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多