将事件处理程序附加到存储在列表中的事件

问题描述:

我想创建一个列表来存储一些事件并通过列表将事件处理程序附加到事件。将事件处理程序附加到存储在列表中的事件

所以我做一个List<dele>添加事件anEvent进去,然后我试图将事件处理程序附加到该事件,但最后anEvent仍然有连接到它的节目输出真没有事件处理程序。但存储在list[0]的代表确实获得了lambda表达式。

public delegate void dele(); 

class Program 
{ 
    static event dele anEvent; 
    static void Main(string[] args) 
    { 
     List<dele> list=new List<dele>(); 
     list.Add(anEvent); 
     list[0]+=()=>{Console.WriteLine("BEEP!");}; 
     Console.WriteLine(anEvent==null); 
    } 
} 

是不是委托引用类型?看来eventhandlerlist[0]是指不同的对象。我想知道为什么。

如果我想anEvent获取事件处理程序时,我将处理程序附加到list[0],我该怎么办?

谢谢!

+0

_The方案产出'True'_不确定??? – TaW

+1

输出是假的我测试了它 –

+0

代表是值类型。 – Enigmativity

委托基本上是一个方法实现的合同。有点像界面是类实现的契约。

CLI(公共语言基础结构)规范说delegates are reference types

委托是一种引用类型,可用于封装指定的 或匿名方法。委托类似于 C++中的函数指针;然而,代表是类型安全的和安全的。对于 代表的应用程序,请参阅代表和常规代表。

看看this的问题,也看看that一。

我已转换的方法成非匿名方法用于调试的原因

public delegate void dele(); 
public static event dele anEvent; 

    static void Main(string[] args) { 
     List<dele> list = new List<dele>(); 
     list.Add(anEvent); 
     list[0] += Dele; 
     list[0].Invoke(); //this actually gets invoked and does not throw! 
     anEvent = list[0]; 
     Console.WriteLine(anEvent == null); //the output is false 
     anEvent.Invoke(); // this also gets s invoked and does not throw 
    } 

private static void Dele() { //this gets invoked 2 times as expected 
    Console.WriteLine("Beep"); // this gets printed after invoking the event 
} 
+0

我很抱歉。语句anEvent = list [0];不应该在那里。我删除它。然后输出将是哔声和真实的。这意味着一个事件没有得到删除和列表[0]得到了,我认为它是正确的?但为什么?委托是引用类型,那么为什么list [0]和anEvent获得不同的值? –

+0

我想我明白了。所以当我将'anEvent'传递给'List.Add'方法时,它实际上复制了事件中的委托,然后我将一个事件处理程序附加到存储在'list [0]'中的委托中,因为委托是一个不可变类型它不会影响'anEvent'中的委托,因此它不起作用。是对的吗? –