简体   繁体   中英

Is it possible to define a generic lambda in C#?

I have some logic in a method that operates on a specified type and I'd like to create a generic lambda that encapsulates the logic. This is the spirit of what I'm trying to do:

public void DoSomething()
{
    // ...

    Func<T> GetTypeName = () => T.GetType().Name;

    GetTypeName<string>();
    GetTypeName<DateTime>();
    GetTypeName<int>();

    // ...
}

I know I can pass the type as a parameter or create a generic method. But I'm interested to know if a lambda can define its own generic parameters. (So I'm not looking for alternatives.) From what I can tell, C# 3.0 doesn't support this.

It is not possible to create a lambda expression which has new generic parameters. You can re-use generic parameters on the containing methods or types but not create new ones.

While Jared Parson's answer is historically correct (2010!), this question is the first hit in Google if you search for "generic lambda C#". While there is no syntax for lambdas to accept additional generic arguments, you can now use local (generic) functions to achieve the same result. As they capture context, they're pretty much what you're looking for.

public void DoSomething()
{
    // ...

    string GetTypeName<T>() => typeof(T).GetType().Name;

    string nameOfString = GetTypeName<string>();
    string nameOfDT = GetTypeName<DateTime>();
    string nameOfInt = GetTypeName<int>();

    // ...
}

While you cannot (yet?) have a generic lambda (see also this answer and one comment to this question ), you can get the same usage syntax. If you define:

public static class TypeNameGetter
{
    public static string GetTypeName<T>()
    {
        return typeof( T ).Name;
    }
}

The you can use it (though using static is C# 6) as:

using static TypeNameGetter;
public class Test
{
    public void Test1()
    {
        var s1 = GetTypeName<int>();
        var s2 = GetTypeName<string>();
    }
}

只有当您的DoSomething方法是通用的或其类是通用的时,才可以执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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