为什么copyOfDelegate是原始委托的副本,而不是原始委托的副本?
public class DelegateTester
{
public delegate void PrintDelegate();
public PrintDelegate PrintCallback;
}
public class Client
{
public void Print()
{
Console.WriteLine("in client");
}
}
static void main()
{
DelegateTester tester = new DelegateTester();
Client client = new Client();
tester.PrintCallback += new DelegateTester.PrintDelegate(client.Print);
tester.PrintCallback += new DelegateTester.PrintDelegate(client.Print);
// copy the delegate
DelegateTester.PrintDelegate copyOfDelegate = tester.PrintCallback;
tester.PrintCallback -= new DelegateTester.PrintDelegate(client.Print);
tester.PrintCallback();
copyOfDelegate.Invoke();
}
答案 0 :(得分:5)
代表是像字符串一样不可变的。 Here is an article..
答案 1 :(得分:3)
我相信委托是不可变的,所以你设置了:
copyOfDelegate = tester.PrintCallback;
然后:
PrintCallback -= new DelegateTester.PrintDelegate(client.Print);
您实际上已将原始委托实例分配给copyOfDelegate
,然后由于不变性而分配给Printcallback
时会创建新委托。