2011-06-14 3 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; 

: 그리고 당신은 실제로 copyOfDelegate 원래 위임 인스턴스를 할당 한

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

등을 한 다음 새를 불변성 때문에 Printcallback에 할당하면 대리인이 만들어집니다.

관련 문제