简体   繁体   English

需要帮助在 C# 中使用 generics 和 lambda 表达式创建扩展方法

[英]Need help creating extension method in C# with generics and lambda expression

I'm pulling all of the advanced features together for this one, but haven't worked with generics or lambda expressions very much:我将所有的高级功能都整合到了一起,但还没有使用 generics 或 lambda 表达式:

Here's example usage of the method I want to create:这是我要创建的方法的示例用法:

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

Here's as far as I've gotten, but Visual Studio is complaining:这是据我所知,但 Visual Studio 抱怨:

在此处输入图像描述

You haven't made your method generic in TResult .您还没有在TResult您的方法通用。 You want something like:你想要这样的东西:

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

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

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