using System;public delegate void MyDelegate1();public interface I1
{
event MyDelegate1 MyEvent;
}public delegate int MyDelegate2(string s);public interface I2
{
event MyDelegate2 MyEvent;
}public class ExplicitEventsSample: I1, I2
{
public event MyDelegate1 MyEvent; // normal implementation of I1.MyEvent. event MyDelegate2 I2.MyEvent // explicit implementation of I2.MyEvent
{
add
{
MyEvent2Storage += value;
}
remove
{
MyEvent2Storage -= value;
}
} private MyDelegate2 MyEvent2Storage; 用接口名定义着代表什么呀,还有请问为什么在着定义的MyEvent2Storage为什么会在上面也可以用那? private void FireEvents()
{
if (MyEvent != null)
MyEvent();
if (MyEvent2Storage != null)
MyEvent2Storage("hello");
}
}public class MyClass
{
public static void Main()
{
}
}
{
event MyDelegate1 MyEvent;
}public delegate int MyDelegate2(string s);public interface I2
{
event MyDelegate2 MyEvent;
}public class ExplicitEventsSample: I1, I2
{
public event MyDelegate1 MyEvent; // normal implementation of I1.MyEvent. event MyDelegate2 I2.MyEvent // explicit implementation of I2.MyEvent
{
add
{
MyEvent2Storage += value;
}
remove
{
MyEvent2Storage -= value;
}
} private MyDelegate2 MyEvent2Storage; 用接口名定义着代表什么呀,还有请问为什么在着定义的MyEvent2Storage为什么会在上面也可以用那? private void FireEvents()
{
if (MyEvent != null)
MyEvent();
if (MyEvent2Storage != null)
MyEvent2Storage("hello");
}
}public class MyClass
{
public static void Main()
{
}
}
private MyDelegate2 MyEvent2Storage;//用接口名定义着代表什么呀,还有请问为什么在着定义的MyEvent2Storage为什么会在上面也可以用那?
此处应该为
private event MyDelegate2 MyEvent2Storage;//用接口名定义着代表什么呀,还有请问为什么在着定义的MyEvent2Storage为什么会在上面也可以用那?
另:
C#不是C++,除了函数内部,其他地方不必要先声明再使用的。
private MyDelegate2 MyEvent2Storage;//用接口名定义着代表什么呀,还有请问为什么在着定义的MyEvent2Storage为什么会在上面也可以用那? 这是显式控制事件的订阅和注销。事件其实就是利用多播委托实现的,就是一个委托链表,里面是一系列订阅的方法指针。
private MyDelegate2 MyEvent2Storage; 这句只是一个对委托链表的引用,并非事件。
而
event MyDelegate2 I2.MyEvent // explicit implementation of I2.MyEvent
{
add
{
MyEvent2Storage += value;
}
remove
{
MyEvent2Storage -= value;
}
}
提供了向委托链表中添加一个委托和删除一个委托的访问器。注意:add和remove必须同时实现。
MyDelegate2 委托
{
void TestMe();
}interface ITest2
{
void TestMe();
}public class Test:ITest
{
public void TestMe
{ Console.Write("0"); } public void ITest1.TestMe()
{ Console.Write("1"); } public void ITest2.TestMe()
{ Console.Write("2"); }
}那么区别就在使用的时候,如果:
Test t = new Test();
t.TestMe();
那么将会输出字符0而如果:
ITest1 t = new Test();
t.TestMe();
那么将会输出字符1而如果:
ITest2 t = new Test();
t.TestMe();
那么将会输出字符2
改为:
public class Test:ITest1, ITest2