Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

c# 3.0 - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>();

    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...