How can I write a generic anonymous method?

后端 未结 4 1841
半阙折子戏
半阙折子戏 2020-12-02 01:56

Specifically, I want to write this:

public Func, T> SelectElement = list => list.First();

But I get a syntax error

4条回答
  •  余生分开走
    2020-12-02 02:30

    Nope, sorry. That would require generic fields or generic properties, which are not features that C# supports. The best you can do is make a generic method that introduces T:

    public Func, T> SelectionMethod() { return list => list.First(); }
    

    And now you can say:

    Func, int> selectInts = SelectionMethod();
    

提交回复
热议问题