简体   繁体   English

如何编写通用的匿名方法?

[英]How can I write a generic anonymous method?

Specifically, I want to write this: 具体来说,我想写这个:

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

But I get a syntax error at T . 但我在T语法错误。 Can't I have a generic anonymous method? 我不能拥有通用的匿名方法吗?

Nope, sorry. 不,谢谢。 That would require generic fields or generic properties, which are not features that C# supports. 这将需要通用字段或通用属性,这些属性不是C#支持的功能。 The best you can do is make a generic method that introduces T: 你能做的最好的事情就是制作一个引入T的通用方法:

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

And now you can say: 现在你可以说:

Func<IList<int>, int> selectInts = SelectionMethod<int>();

Of course you can, but T must be known: 你当然可以,但必须知道T

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 . 但是仍然有人在编译时需要知道这个T

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. 只有首先在方法名称中声明了T才能使用T作为返回参数。

Even though it looks like the return type is declared before the actual method, the compiler doesn't read it that way. 即使看起来在实际方法之前声明了返回类型,编译器也不会以这种方式读取它。

    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}");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM