通过 COM 对象的反射获取属性名称 [英] Get property names via reflection of a COM object

查看:23
本文介绍了通过 COM 对象的反射获取属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中通过 COM 对象的反射读出所有属性名称?如果我知道名字,我就知道如何获得财产.

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

这种方式不适用于 Com-Objects.如果我执行 GetMembers() 我得到这些成员:

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

问候克里斯

推荐答案

您获得了 __ComObject 类的成员,该类是 RCW 的基础 .NET 类.

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

COM 对反射有一点支持,只要 COM 组件类实现 IDispatch,即自动化接口.这并不罕见,它是脚本语言用来进行调用的接口.IDispatch.GetIDsOfNames() 总是被实现,但你必须预先知道成员的名字.IDispatch.GetTypeInfo() 允许访问 coclass 的类型库,但并不总是实现.将类型库信息转换为元数据是一门不完美的艺术,这是 .NET 要求您预先使用 Tlbimp.exe 执行此操作的核心原因.如果您想采用运行时方法,那么您可能会受益于 Tlbimp 托管版本的源代码,此处提供.

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.

在构建时预先执行此操作总是最好的,您可以通过添加对类型库的引用(通常嵌入在可执行文件中)或自己运行 Tlbimp.exe 来实现.现在您获得了一个 .NET 互操作包装类,它具有底层 COM 协类和接口的所有成员.在这一点上,您可能不再需要反射:)

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

这篇关于通过 COM 对象的反射获取属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆