Cast delegate to Func in C#

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

    The problem is that:

    SomeDelegate a = Inc;
    

    Isn't actually a cast. It's the short-form of:

    SomeDelegate a = new SomeDelegate(Inc);
    

    Therefore there's no cast. A simple solution to your problem can be this (in C# 3.0)

    Func f = i=>a(i);
    

提交回复
热议问题