Cast delegate to Func in C#

后端 未结 8 2069
小蘑菇
小蘑菇 2020-12-01 12:03

I have code:

public delegate int SomeDelegate(int p);

public static int Inc(int p) {
    return p + 1;
}

I can cast Inc to

8条回答
  •  攒了一身酷
    2020-12-01 12:17

    It is the same kind of problem as this:

    public delegate int SomeDelegate1(int p);
    public delegate int SomeDelegate2(int p);
    ...
      SomeDelegate1 a = new SomeDelegate1(Inc);
      SomeDelegate2 b = (SomeDelegate2)a;  // CS0030
    

    which is the same kind of problem as:

    public class A { int prop { get; set; } }
    public class B { int prop { get; set; } }
    ...
      A obja = new A();
      B objb = (B)obja;  // CS0029
    

    Objects cannot be casted from one type to an unrelated other type, even though the types are otherwise completely compatible. For lack of a better term: an object has type identity that it carries along at runtime. That identity cannot be changed after the object is created. The visible manifestation of this identity is Object.GetType().

提交回复
热议问题