COM互操作 - 具有相同名称的事件和属性

时间:2017-12-07 13:07:35

标签: c# com-interop

我有一个用C ++ / ATL实现的旧COM对象。该对象具有事件和具有相同名称的属性。这不是COM中的问题。

在C#中,属性有效地隐藏了事件,因此似乎无法添加事件处理程序。

C#中是否有解决此问题的方法?

(有趣的是,您可以使用WithEvents和Handles机制在VB.NET中处理它,但这对C#没有帮助。)

更新

这是事件接口(IDL)的定义。

// Event interface to be implemented by channel objects.
[
  uuid(FF34BE60-C584-4f45-B3A1-231F0E08BE83),
  helpstring("IChannelEvents Interface"),
]
dispinterface IChannelEvents
{
  properties:
  methods:
  [id(1), helpstring("")]
  void OnlineValue ( [in] double        dValue,
                     [in] double        dMax,
                     [in] double        dMin,
                     [in] BSTR          Unit,
                     [in] VARIANT_BOOL  bOverloaded );

  [id(2), helpstring("")]
  void MeasuredExcitation ( [in] double        dValue,
                            [in] VARIANT_BOOL  bValueValid,
                            [in] VARIANT_BOOL  bInRange );

  [id(3), helpstring("")]
  void MultipleOnlineValues ( [in] VARIANT        Values,
                              [in] BSTR           Unit );
} ;

这是COM对象(IDL)的定义

[
  uuid(2B725FC4-6FE6-4D53-9528-F098F04E98EE),
  helpstring("Channel Class")
]
coclass Channel
{
  [default] interface IChannel;
  [default, source ] dispinterface IChannelEvents ;
};

接口IChannel包含名为OnlineValue的属性。我不认为确切的定义很重要。

汉斯似乎在暗示这样的事情:

class EventTest
{
  void Test()
  {
    Channel         c  = null ;
    IChannelEvents  ce = c as IChannelEvents ;
    ce.OnlineValue += this.OnlineValue ;
  }

  void OnlineValue ( double        dValue,
                     double        dMax,
                     double        dMin,
                     string        Unit,
                     bool          bOverloaded )
  {
  }
} 

这会产生错误

Error CS1656    
Cannot assign to 'OnlineValue' because it is a 'method group'

这段代码对我来说真的没有意义,因为 - 正如Hans所说 - 通道对象没有实现事件接口,那么为什么从Channel到IChannelEvents的转换工作呢?

1 个答案:

答案 0 :(得分:2)

我找到了一个解决方案,这可能就是Hans Passant的建议。

事件接口名为IChannelEvents。类型库导入器生成名为IChannelEvents_Event。

的接口

反汇编,接口定义如下:

Product minProductPrice = producs.stream()
        .min((o1, o2) -> o1.price.compareTo(o2.price)).get();

我可以将COM对象强制转换为此接口,并添加一个事件处理程序,如下所示。

[ComEventInterface(typeof(IChannelEvents), typeof(IChannelEvents_EventProvider)), ComVisible(false), TypeLibType(16)]
public interface IChannelEvents_Event
{
  event IChannelEvents_OnlineValueEventHandler OnlineValue;
  event IChannelEvents_MeasuredExcitationEventHandler MeasuredExcitation;
  event IChannelEvents_MultipleOnlineValuesEventHandler MultipleOnlineValues;
}

此界面不会显示在intellisense中,但在输入后,visual Studio会设置文本颜色以指示它识别该类型。