Cast delegate to Func in C#

后端 未结 8 2066
小蘑菇
小蘑菇 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:28

    SomeDelegate a = Inc;
    Func b = Inc;
    

    is short for

    SomeDelegate a = new SomeDelegate(Inc); // no cast here
    Func b = new Func(Inc);
    

    You can't cast an instance of SomeDelegate to a Func for the same reason you can't cast a string to a Dictionary -- they're different types.

    This works:

    Func c = x => a(x);
    

    which is syntactic sugar for

    class MyLambda
    {
       SomeDelegate a;
       public MyLambda(SomeDelegate a) { this.a = a; }
       public int Invoke(int x) { return this.a(x); }
    }
    
    Func c = new Func(new MyLambda(a).Invoke);
    

提交回复
热议问题