C# 由同一委托类型生成的每个事件是否都有';谁是自己的多播代理?
如果我有类似于:C# 由同一委托类型生成的每个事件是否都有';谁是自己的多播代理?,c#,events,delegates,C#,Events,Delegates,如果我有类似于: static class Program { public static delegate void TestHandler(); public static event TestHandler TestEvent; public static event TestHandler TestEvent1; public static event TestHandler TestEvent2; static void Main(s
static class Program
{
public static delegate void TestHandler();
public static event TestHandler TestEvent;
public static event TestHandler TestEvent1;
public static event TestHandler TestEvent2;
static void Main(string[] args)
{
TestEvent += DoSomething1;
TestEvent1 += DoSomething2;
TestEvent2 += DoSomething3;
Trigger();
Console.ReadLine();
}
public static void Trigger()
{
TestEvent();
TestEvent1();
TestEvent2();
}
private static void DoSomething3()
{
Console.WriteLine("Something 3 was done");
}
private static void DoSomething2()
{
Console.WriteLine("Something 2 was done");
}
private static void DoSomething1()
{
Console.WriteLine("Something 1 was done");
}
由相同类型生成的每个事件是否都有自己的多播委托?如何将每个事件的调用列表与相同的委托类型分开?
委托实际上是类。因此,在您的例子中,有一种类型是为TestHandler
delegate创建的。该类有三个不同的实例
您可以在生成的IL代码中轻松看到这一点:
如您所见,有一个TestHandler
类型,并且有三个该类型的字段。因此,它们共享相同的类型,但它们是完全独立的…是的,每个事件都有自己的多播委托支持字段。如果事件类型(因此字段类型)相同,则不会改变这一点
守则:
public delegate void TestHandler();
static class Program
{
public static event TestHandler TestEvent;
public static event TestHandler TestEvent1;
public static event TestHandler TestEvent2;
}
或多或少意味着:
public delegate void TestHandler();
static class Program
{
// backing fields with the same names:
private static TestHandler TestEvent;
private static TestHandler TestEvent1;
private static TestHandler TestEvent2;
// each event is really a pair of two "methods" (accessors)
public static event TestHandler TestEvent
{
add
{
// smart code to access the private field in a safe way,
// combining parameter 'value' into that
}
remove
{
// smart code to access the private field in a safe way,
// taking out parameter 'value' from that
}
}
public static event TestHandler TestEvent1
{
add
{
// smart code to access the private field in a safe way,
// combining parameter 'value' into that
}
remove
{
// smart code to access the private field in a safe way,
// taking out parameter 'value' from that
}
}
public static event TestHandler TestEvent2
{
add
{
// smart code to access the private field in a safe way,
// combining parameter 'value' into that
}
remove
{
// smart code to access the private field in a safe way,
// taking out parameter 'value' from that
}
}
}
不能声明委托类型静态
!您的代理类型与System.Action
具有相同的签名和返回类型,因此您可以改用该类型。图中还有三个private
字段(靠近顶部,用带S的“菱形”(表示static
)显示),它们与事件(程序底部的“三角形”)本身具有相同的名称。每个私有字段都是对包含自己调用列表的对象的引用。