在 C# 中包装 COM 对象/动态类型
我目前正在托管代码中使用 COM 对象,并为此使用新的动态类型。这在某些领域效果很好,但在其他领域可能会出现问题。
我在考虑如何才能两全其美,即动态类型(后期绑定)的灵活性以及对 RCW(早期绑定)的支持,以
某种方式将动态类型包装在更易于管理的结构中。我想知道是否有一个首选方法(如果这是一个好主意)或者我应该考虑哪些事情。
到目前为止,我提出的两个基本想法如下:
首先,创建一个静态类,允许我以托管方式调用动态类型的方法。
public static class ComObjectWrapper
{
public static void SomeMethod(dynamic comObject, int x)
{
comObject.someMethod(x);
}
public static bool GetSomeProp(dynamic comObject)
{
comObject.getSomeProp();
}
public static void SetSomeProp(dynamic comObject, bool foo)
{
comObject.setSomeProp(foo);
}
}
其次,创建一个使用 com 对象构造的类,然后将其所有成员映射到托管属性、方法等。
public class ComObjectWrapper
{
private dynamic comObject = null;
public ComObjectWrapper(dynamic comObject)
{
this.comObject = comObject;
}
public void SomeMethod(int x)
{
comObject.someMethod(x);
}
public bool SomeProp
{
get
{
return comObject.getSomeProp();
}
set
{
comObject.setSomeProp(value);
}
}
}
还有其他方法可以解决此问题吗?我是不是错过了一些愚蠢的事情!?
I am currently working with COM objects in managed code and am using the new dynamic type for this. This works well in some areas but can be an issue in others.
I was think about how I could get the best of both worlds, the flexibility of the dynamic type (late bound) with the support for say, an RCW (early bound)
Somehow wrapping the dynamic type in a more manageable stucture. I was wondering if there was a preferred method for this (if it is even a good idea) or what things I should consider.
The two basic ideas I came up with so far as follows:
Firstly, creating a static class that allows me to call the methods of the dynamic type in a managed way.
public static class ComObjectWrapper
{
public static void SomeMethod(dynamic comObject, int x)
{
comObject.someMethod(x);
}
public static bool GetSomeProp(dynamic comObject)
{
comObject.getSomeProp();
}
public static void SetSomeProp(dynamic comObject, bool foo)
{
comObject.setSomeProp(foo);
}
}
Secondly, creating a class that is constructed using the com object, then mapping all its members to managed properties, methods, etc.
public class ComObjectWrapper
{
private dynamic comObject = null;
public ComObjectWrapper(dynamic comObject)
{
this.comObject = comObject;
}
public void SomeMethod(int x)
{
comObject.someMethod(x);
}
public bool SomeProp
{
get
{
return comObject.getSomeProp();
}
set
{
comObject.setSomeProp(value);
}
}
}
Are there other ways to approach this? Am I missing something stupid!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
开源框架Impromptu-Interface 将用静态接口包装动态对象,以便所有接口中静态定义的成员使用 dlr 转发到动态对象。
创建你的界面
然后你需要包装你的 com 对象的地方包括 ImpromptuInterface
最后包装它:
The opensource framework Impromptu-Interface will wrap a dynamic object with a static interface such that all the statically defined members from the interface use the dlr to forward to the dynamic object.
Create Your interface
Then where you need to wrap your com object include ImpromptuInterface
And finally to wrap it: