问题描述
|
为什么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();
}
解决方法
我相信代表是一成不变的,所以您在哪里设置:
copyOfDelegate = tester.PrintCallback;
接着:
PrintCallback -= new DelegateTester.PrintDelegate(client.Print);
您实际上已经将原始委托实例分配给copyOfDelegate
,然后由于不可变性而在分配给Printcallback
时创建了一个新委托。
, 代表像字符串一样是不可变的。这是一篇文章。