关于委托的+=操作
举个简单的例子:
class Program { public static EventHandler eh = null; public void test(object sender, EventArgs e) { Console.WriteLine(sender.ToString()); } static void Main(string[] args) { Program p = new Program(); Dictionary<string, object> d = new Dictionary<string, object>(); eh = p.test; d.Add("other", eh); eh += p.test; eh("I am the Original", null); eh = d["other"] as EventHandler; Console.WriteLine("--------------------------------------------------"); eh("I am the Other", null); Console.Read(); } }
上面代码的Main函数经过 reflector 查看后如下:
private static void Main(string[] args) { Program p = new Program(); Dictionary<string, object> d = new Dictionary<string, object>(); eh = new EventHandler(p.test); d.Add("other", eh); eh = (EventHandler) Delegate.Combine(eh, new EventHandler(p.test)); eh("I am the Original", null); eh = d["other"] as EventHandler; Console.WriteLine("--------------------------------------------------"); eh("I am the Other", null); Console.Read(); }也就是说 经过+=操作后eh已经指向新的对象了(通过 Delegaate.Combine 合并成一个新的对象),而字典中保存的eh 指向原始的对象,像上文一样使用委托 造成了不一致,这很有点像.net 中
System.String类型。

浙公网安备 33010602011771号