通过反射在C#铸造系统.__ ComObject [英] Casting a System.__ComObject in C# via reflection

查看:122
本文介绍了通过反射在C#铸造系统.__ ComObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图投系统.__ ComObject 来使用反射接口类型。我已经尝试使用 Convert.ChangeType(对象类型),但C#然后抛出这个错误:

I'm attempting to cast a System.__ComObject to an interface type using reflection. I have tried using Convert.ChangeType(Object,Type) but c# then throws this error:

System.InvalidCastException:对象
必须实现IConvertible

System.InvalidCastException: Object must implement IConvertible.

那么,有没有投一般的任何可能的方式 __使用反射到其正确的类型,所以我可以再调用通过反射它的方法ComObject ?是的,它必须要通过不涉及提前告知时间的对象类型是什么,编译器的方法完成了!

So is there any possible way to cast a general __ComObject using reflection to its correct type so i can then call its methods via reflection? And yes, it has to be done via a method which doesn't involve telling the compiler ahead of time what the object type is!

推荐答案

在一般情况下,没有。

_ComObject需要实现的.NET运行时知道的接口。这要么是你从的QueryInterface 得到一个接口或的IDispatch

The _ComObject needs to implement an interface which the .Net runtime knows about. This will either be an interface which you get from QueryInterface or IDispatch.

如果是前者,你必须知道的接口是什么,然后你要描述接口使用的 ComImportAttribute

If it's the former, you have to know what the interface is, and then you have to describe the interface to .Net using the ComImportAttribute on the interface.

如果该COM对象实现的IDispatch ,可以动态调用它的成员。在.NET 4.0及以上,这可以很容易地通过动态关键字完成。如果您使用的是.NET的早期版本,你可以调用 InvokeMember() 上转换为的或者通过的GetType返回输入http:// MSDN .microsoft.com / EN-US /库/ system.reflection.ireflect.aspx相对=nofollow> IReflect ,并使用该接口来调用方法

If the COM object implements IDispatch, you can dynamically invoke members on it. In .Net 4.0 and above, this can be done easily by using the dynamic keyword. If you are using an earlier version of .Net, you can call InvokeMember() on the type returned by GetType() or else cast to IReflect and use that interface to call methods.

最好的情况是,如果你得到一个运行时可调用包装(RCW)的COM对象,通过运行 tlbimp.exe是自己的COM库或COM库笔者得到一个主Interop大会(PIA)它,通常。

The best case is if you get a Runtime Callable Wrapper (RCW) for the COM object, either by running tlbimp.exe yourself on the COM library or getting a Primary Interop Assembly (PIA) for it, usually from the COM library author.

这篇关于通过反射在C#铸造系统.__ ComObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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