How can I write a generic anonymous method?

后端 未结 4 1831
半阙折子戏
半阙折子戏 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

    You declared only the return type as generic.

    Try this:

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

    The name of the thing you are declaring must include the type parameters for it to be a generic. The compiler supports only generic classes, and generic methods.

    So, for a generic class you must have

    class MyGeneric { 
       // You can use T here now
       public T MyField;
     }
    

    Or, for methods

    public T MyGenericMethod( /* Parameters */ ) { return T; }
    

    You can use T as the return parameter, only if it was declared in the method name first.

    Even though it looks like the return type is declared before the actual method, the compiler doesn't read it that way.

提交回复
热议问题