如果我有类似的话:
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");
}
每个事件是否都是相同类型,是否拥有自己的多播委托?如何为同一个委托类型的每个事件分隔调用列表?
答案 0 :(得分:1)
Delegates
实际上是类。因此,在您的情况下,为TestHandler
委托创建了一种类型。该类有三种不同的实例。
您可以在生成的IL代码中轻松看到这一点:
正如您所看到的那样,有TestHandler
类型,并且该类型有三个字段。所以它们共享相同的类型,但它们是完全分开的......
答案 1 :(得分:1)
是的,每个event
都有自己的多播委托支持字段。事件类型(因此字段类型)相同,不会改变它。
代码:
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
}
}
}