我有一个用C++/ATL实现的旧COM对象。对象具有一个具有相同名称的事件和属性。这在COM中不是问题。
在C#中,该属性实际上隐藏了事件,因此似乎不可能添加事件处理程序。
在C#中有解决这个问题的方法吗?
(有趣的是,您可以在VB.NET中使用WithEvents和Handles机制来处理它,但这对我在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'这段代码对我来说没有什么意义,因为--正如汉斯所说--通道对象没有实现事件接口,那么为什么从通道到IChannelEvents的转换会工作呢?
发布于 2017-12-08 10:29:47
我找到了一个解决办法,这可能就是汉斯·帕桑特的建议。
事件接口名为IChannelEvents。类型库导入程序生成一个名为IChannelEvents_Event的接口。
分解后,接口定义如下:
[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;
}我可以将COM对象强制转换到这个接口,并添加一个事件处理程序,如下所示。
class EventTest
{
void Test()
{
Channel c = null ;
IChannelEvents_Event ee = c as IChannelEvents_Event ;
ee.OnlineValue += OnlineValue ;
}
void OnlineValue ( double dValue,
double dMax,
double dMin,
string Unit,
bool bOverloaded )
{
}
}此接口不显示在intellisense中,但在输入该接口后,visual将文本颜色设置为指示它识别该类型。
https://stackoverflow.com/questions/47695842
复制相似问题