Пример кода рассказывает историю вопроса. Вот он как Скрипка .
Я ожидал, что Действия будут вести себя как "нормальные" экземпляры ссылочного типа , такие как 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