本文介绍了为什么.net委托分配运算符未将引用分配给原始委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么copyOfDelegate是原始委托的副本,而不是原始委托的引用副本?
Why the copyOfDelegate is a copy of the original delegate, instead of the reference copy of the original one?
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();
}
推荐答案
我相信代表是不可变的,因此,在您设置的位置:
I believe delegates are immutable, so where you have set:
copyOfDelegate = tester.PrintCallback;
然后:
PrintCallback -= new DelegateTester.PrintDelegate(client.Print);
您实际上已将原始委托实例分配给 copyOfDelegate
,然后由于不可变性而将其分配给 Printcallback
时,将创建一个新的委托。
You've actually assigned the original delegate instance to copyOfDelegate
, and then a new delegate is created when you assign to Printcallback
because of the immutability.
这篇关于为什么.net委托分配运算符未将引用分配给原始委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!