当要实现两个具有同名事件的接口时,也需要用到事件属性。在这种情况下,必须使用显式实现事件属性。
但是,在显式地实现接口中的事件时,您需要提供添加和移除方法。
示例
| C# | 复制代码 |
|---|---|
public delegate void Delegate1();
public delegate int Delegate2(string s);
public interface I1
{
event Delegate1 TestEvent;
}
public interface I2
{
event Delegate2 TestEvent;
}
public class ExplicitEventsSample : I1, I2
{
public event Delegate1 TestEvent; // normal implementation of I1.TestEvent.
private Delegate2 TestEvent2Storage; // underlying storage for I2.TestEvent.
event Delegate2 I2.TestEvent // explicit implementation of I2.TestEvent.
{
add
{
TestEvent2Storage += value;
}
remove
{
TestEvent2Storage -= value;
}
}
private void FireEvents()
{
if (TestEvent != null)
{
TestEvent();
}
if (TestEvent2Storage != null)
{
TestEvent2Storage("hello");
}
}
}
| |