Why are all Delegate types incompatible with each other?

后端 未结 3 1626
迷失自我
迷失自我 2021-02-13 14:02

In C# all delegate types are incompatible with one another, even if they have the same signature. As an example:

delegate void D1();
delegate void D2();

D1 d1          


        
3条回答
  •  心在旅途
    2021-02-13 14:39

    Basically because the compiler makes two classes for you. The same reason you can't do:

    class A {}
    class B {}
    
    void Main()
    {
        A a = new A();
        B b = a;
    }
    

    For example, the following code

    void Main() {}
    
    delegate void D();
    class C {}
    

    The IL code is:

    D.Invoke:
    
    D.BeginInvoke:
    
    D.EndInvoke:
    
    D..ctor:
    
    C..ctor:
    IL_0000:  ldarg.0     
    IL_0001:  call        System.Object..ctor
    IL_0006:  ret         
    

提交回复
热议问题