2011-06-14 45 views
1

为什么copyOfDelegate是原始代理的副本,而不是原始副本的副本?为什么.net委托赋值运算符不会将引用分配给原始委托?

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(); 
    } 

回答

3

我相信代表是不可改变的,所以,你必须设置:

copyOfDelegate = tester.PrintCallback; 

然后:

PrintCallback -= new DelegateTester.PrintDelegate(client.Print); 

你实际分配原委托实例来copyOfDelegate,然后一个新的由于不可变性,当您将其分配给Printcallback时,会创建代表。