Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

c# - Get property names via reflection of a COM object

How can I read out all property names via reflection of an COM Object in C#? I know how to get the property if I know the name.

comObject.GetType().InvokeMember("PropertyName", System.Reflection.BindingFlags.GetProperty, null, comObject, null);

but what is when I want to dump all properties?

PropertyInfo[] properties = t.GetProperties();

This way didn't work with Com-Objects. If I do a GetMembers() I get these Members:

Name: GetLifetimeService
Name: InitializeLifetimeService
Name: CreateObjRef
Name: ToString
Name: Equals
Name: GetHashCode
Name: GetType

regards Chris

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You got the members of the __ComObject class, the underlying .NET class for an RCW.

COM has a wee bit support for reflection, as long as the COM coclass implements IDispatch, the Automation interface. Not unusual, it is the interface that scripting languages use to make calls. IDispatch.GetIDsOfNames() is always implemented, but you have to know the name of the member up front. IDispatch.GetTypeInfo() gives access to the type library for the coclass, but isn't always implemented. Translation of type library info to metadata is an imperfect art, the core reason why .NET wants you to do this upfront with Tlbimp.exe. If you want to pursue a runtime approach then you'll probably benefit from the source for the managed version of Tlbimp, available here.

Doing this up front at build time is always best, you do so by adding a reference to the type library (usually embedded in the executable file) or by running Tlbimp.exe yourself. Now you got a .NET interop wrapper class that has all of the members of the underlying COM coclass and interfaces. At which point you probably don't need reflection anymore :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...