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

Ron*_*rby 0 c# generics lambda extension-methods

我将所有高级功能集中在一起,但是没有使用泛型或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
Run Code Online (Sandbox Code Playgroud)

就我所知,但是Visual Studio抱怨道:

在此输入图像描述

Jon*_*eet 5

您尚未将方法设为通用TResult.你想要的东西:

public static TResult TryGetOrDefault<TSource, TResult>
    (this TSource obj, Expression<Func<TSource, TResult>> expression)
Run Code Online (Sandbox Code Playgroud)