【问题标题】:Need help creating extension method in C# with generics and lambda expression需要帮助在 C# 中使用泛型和 lambda 表达式创建扩展方法
【发布时间】:2011-07-19 20:09:43
【问题描述】:

我将所有高级功能都整合到了这一项中,但我并没有非常多地使用泛型或 lambda 表达式:

这是我要创建的方法的示例用法:

MyClass mc = null;
int x = mc.TryGetOrDefault(z => z.This.That.TheOther); // z is a reference to mc
// the code has not failed at this point and the value of x is 0 (int's default)
// had mc and all of the properties expressed in the lambda expression been initialized
// x would be equal to mc.This.That.TheOther's value

据我所知,但 Visual Studio 抱怨:

【问题讨论】:

    标签: c# generics lambda extension-methods


    【解决方案1】:

    您还没有在TResult 中使您的方法通用。你想要这样的东西:

    public static TResult TryGetOrDefault<TSource, TResult>
        (this TSource obj, Expression<Func<TSource, TResult>> expression)
    

    【讨论】:

    • 你刚刚把它变成了一个全新的问题,Ronnie。我认为 Jon 已经完美地回答了第一个问题。
    • 我认为问题的范围以我的最终结果为中心,并且由于 StackOverflow 将自己吹捧为类似于 wiki,我可以更新问题。等待我的下一个网址?
    • @Ronnie:您可以编辑现有问题 - 但您提出了一个 问题,这根本不是一回事。
    • 知道了。谢谢您的帮助。我又问了一个问题。
    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多