How can I add functionality to COM object in c#?

元气小坏坏 提交于 2019-12-25 18:31:38

问题


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.

Initially my intention was to inherit from the COM object class, but I found out it was not so straight forward (for example here).

Presently, I have two interfaces (namely IComAuto and ComAuto) and an associated class (ComAutoClass).

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);
    }
    ...
}

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.

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.

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


回答1:


Sounds like a perfect use case for extension methods:

public static class ComAutoExtensions
{
    public static short Method1( this ComAuto com, object param )
    {
        return com.GetShortValue( param );
    }
}


来源:https://stackoverflow.com/questions/40890420/how-can-i-add-functionality-to-com-object-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!