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

时间:2011-07-19 20:09:43

标签: 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

据我所知,但Visual Studio抱怨道:

enter image description here

1 个答案:

答案 0 :(得分:5)

您尚未在TResult中使您的方法具有通用性。你想要这样的东西:

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