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&开发者_运维技巧gt;();
// ...
}
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.
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>();
// ...
}
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 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>();
}
}
This is only possible when your DoSomething
method is generic or its class is generic.
精彩评论