如何在C#中向COM对象添加功能? [英] How can I add functionality to COM object in c#?
问题描述
我是COM和c#的新手,我想向第三方程序公开的COM对象添加功能。
I am new to COM and c# and I would like to add functionality to a COM object that is exposed by a third-party program.
最初,我的意图是从COM对象类继承,但是我发现它不是那么简单(例如,此处)。
Initially my intention was to inherit from the COM object class, but I found out it was not so straight forward (for example here).
目前,我有两个界面(即 IComAuto
和 ComAuto
)和关联的类( ComAutoClass
)。
Presently, I have two interfaces (namely IComAuto
and ComAuto
) and an associated class (ComAutoClass
).
要将自定义方法添加到 ComAuto
对象,我创建了一个类 ComObjectWrapper
,该类从该接口继承并通过存储 ComAuto $ c来实现
To add my custom methods to ComAuto
objects, I have created a class ComObjectWrapper
that inherits from this interface and implements it by storing a ComAuto
object in a private field.
class ComObjectWrapper : ComAuto
{
private readonly ComAuto ComObj;
public ComObjectWrapper() : base()
{
ComObj = new ComAuto();
}
public short method1(object param)
{
return ComObj.method1(param);
}
...
}
我有一种感觉这不是执行此操作的最佳方法,因为我需要将对原始方法的所有调用重定向到内部 ComAuto
对象。
I have a feeling this is not the best way to do this as I need to redirect any call to an original method to the internal ComAuto
object.
我尝试通过设置 Embed Interop类型直接从
ComAutoClass
继承在VS2015中将code>属性设置为 false
。当我已经编写的代码期望 string
时,这导致了一些方法以 object
的形式返回值。因此,我将不得不遍历所有编写的代码,以对 string
添加一些强制类型转换。这不是很理想,而且我对嵌入式Interop类型
并不完全了解。
I tried alternatively to inherit from ComAutoClass
directly by setting the Embed Interop types
property to false
in VS2015. This led some method to return values as object
when the code I have already written expects string
. I would therefore have to go through all the written code to add some casts to string
. Not ideal and moreover I don't have a full understanding of what Embed Interop types
is.
我会很感激如果有人可以对此有所启发或指向一些有用的文章(到目前为止,我在MSDN上发现的内容对于像我这样的初学者来说有点神秘)。
I would appreciate if anyone could shed some light on this or point to some useful article (what I have found so far on MSDN sounds a bit cryptic for a beginner like me).
推荐答案
听起来像扩展方法:
public static class ComAutoExtensions
{
public static short Method1( this ComAuto com, object param )
{
return com.GetShortValue( param );
}
}
这篇关于如何在C#中向COM对象添加功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!