How return the type of a System.__COMObject in Sys

2019-01-25 21:19发布

问题:

I'm doing a program and I want to do a Reflection, but for this, I need an Object of the Type class, right? to use the .GetProperties() method... So I tryed this:

Type typeName = simObjects.getType();

But the .GetType() is returning "System.__COMObject". And this is not helpfull. The same happens with .typeof(). I search and found another code, this one:

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

But this method return a String, and I need it in System.Type, Can any genious please help me?

回答1:

Well, i know its a late answear, i solve my problem some time ago, i'll answear, hope it can help someone.

I did not use reflextion as i wish, but its working pretty fine.

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")
           {
           }
        } 
    }
}

This code return the name of the attributes, for example, imagine that my COMObject have this attributes:

int age;
string name;
Son Phill;

and Son have:

int age;
string name;

in the first loop, the descrip.Name will be "age", "name" and "Phill", and in the second (supose that the condiiton return true with "Son"), "age" and "name".

Hope this helps someone.



回答2:

See this link on how to get the type:

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

See this SO answer regarding COM objects and reflection:

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

Also, do you know what the properties are ahead of time? If so you may (I've never tried it with a COM object) be able to use Dynamics instead to access the properties.

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

EDIT: This link explains using dynamics and COM

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

In case it disappears:

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