How can I write a generic anonymous method?

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

    Of course you can, but T must be known:

    class Foo<T>
    {
        public Func<IList<T>, T> SelectionMethod = list => list.First();
    }
    

    As an alternative you could use a generic method if you don't want to make the containing class generic:

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

    But still someone at compile time will need to know this T.

    0 讨论(0)
  • 2020-12-02 02:20
        public static void SomeContainerFunction()
        {
            const string NULL_VALUE = (string)null;
    
            Type GetValueType<T>(T value) => value?.GetType() ?? typeof(T);
    
            var typeOfNullValue = GetValueType(NULL_VALUE);
    
            Debug.WriteLine($"Value: {NULL_VALUE}, Type: {typeOfNullValue}");
        }
    
    0 讨论(0)
  • 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<IList<T>, T> SelectionMethod<T>() { return list => list.First(); }
    

    And now you can say:

    Func<IList<int>, int> selectInts = SelectionMethod<int>();
    
    0 讨论(0)
  • 2020-12-02 02:30

    You declared only the return type as generic.

    Try this:

    public Func<IList<T>, T> SelectionMethod<T>() { 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<T> { 
       // You can use T here now
       public T MyField;
     }
    

    Or, for methods

    public T MyGenericMethod<T>( /* 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.

    0 讨论(0)
提交回复
热议问题