代码示例讲述了问题的故事。 Here it is as a Fiddle。
我预计行动的行为就像&#34;正常&#34;引用类型实例such as List<Action>
.
using System;
public class Program
{
static Action action1;
static Action action2;
public static void Main()
{
// the Both method goes to both action1 and action2
// that is what I expected
action1 = Both;
action2 = action1;
// anything now assigned to action1 only goes to action1
action1 += OnlyAction1;
// and anything now assigned to action2 only goes to action2
action2 += OnlyAction2;
foreach (var d in action1.GetInvocationList())
Console.WriteLine(d.Method.Name);
foreach (var d in action2.GetInvocationList())
Console.WriteLine(d.Method.Name);
// since both actions have the same HashCode,
// I expected both actions to have the same invocation list,
Console.WriteLine(action1.GetHashCode());
Console.WriteLine(action2.GetHashCode());
}
public static void Both() {}
public static void OnlyAction1() {}
public static void OnlyAction2() { }
}
输出:
Both
OnlyAction1
Both
OnlyAction2
828401262
828401262
答案 0 :(得分:2)
等哈希码并不是说对象是相等的。
如果两个对象比较相等,则每个对象的GetHashCode方法 对象必须返回相同的值。但是,如果两个对象没有 比较相同,两个对象的GetHashCode方法不 必须返回不同的值。
不同的哈希码表示对象不同,但反之亦然。
阅读更多GetHashCode方法:https://mysite.maindomain.com:8080/get-user/10
来自https://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx回答:
委托是不可变的,因此在该代码中获得的引用是 保证不会改变。如果用户之后订阅或取消订阅 空检查,将创建一个新的委托并设置为该事件。