2014-09-10 29 views
4

我在做一個程序,我想做一個Reflection,但爲此,我需要一個Type類的對象,對嗎?使用.GetProperties()方法。所以我tryed這一點:如何在C#中返回System.Type中System.__ COMObject的類型

Type typeName = simObjects.getType();

但.GetType()將返回 「系統.__ COMObject」。這不是有用的。 .typeof()會發生同樣的情況。我搜索,發現另一個代碼,這一個:

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

但這種方法返回一個字符串,我需要它的System.Type,可以在任何天才要比幫幫我嗎?

+0

COM不支持Reflection。 – 2014-09-10 18:09:24

+0

http://www.add-in-express.com/creating-addins-blog/2011/12/20/type-name-system-comobject/ – MethodMan 2014-09-10 18:14:20

+0

@HansPassant您可以使用CustomMarshaler將COM ITypeInfo(可用在實現IDispatch的COM對象上)轉換爲.NET反射類型,如[本答案](http://stackoverflow.com/a/14208030/3175562)和[本項目]中所示(http://www.codeproject.com) /條/ 523417 /反射與 - IDispatch的基礎-COM對象)。 – Mike 2016-03-30 15:21:27

回答

2

嗯,我知道它的後期answear,我解決我的問題前段時間,我會回答,希望它能幫助別人。

我沒有使用反射,因爲我希望,但它的工作很好。

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; 
在第一循環

,描述名稱將是「年齡」,「名稱」和「Phill」,並且在第二個(假設該條件與「兒子」,「年齡」和「名稱」一致)。

希望這可以幫助別人。

0

參見如何獲取類型此鏈接:

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

看到這個SO回答關於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); 
+0

我看到這個鏈接,沒有幫助,這個例子只對Excel有幫助,並且我沒有對excel進行任何修改......=( – Jovita 2014-09-10 18:31:03

+0

)只要你知道什麼屬性被調用,相同的技術就可以應用到任何類型的對象上動態屬性是在運行時進行評估的,只需將你的COM對象分配給動態並訪問它的屬性,就像任何POCO – DVK 2014-09-10 18:40:46

+0

我正在閱讀此鏈接,我不確定是否有幫助,但是無論如何謝謝 – Jovita 2014-09-10 19:39:09

相關問題