[英]COM interop - event and property with same name
我有一個用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'
這段代碼對我來說真的沒有意義,因為-正如漢斯所說-通道對象沒有實現事件接口,那么為什么從Channel到IChannelEvents的轉換起作用?
我找到了一個解決方案,這可能是漢斯·帕桑特(Hans Passant)所建議的。
該事件接口名為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 )
{
}
}
此界面不會以智能感知顯示,但是輸入后,Visual Studio會設置文本顏色以指示它可以識別類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.