C# 获取扩展方法的属性';这是她第一次和lambda吵架?(x=>;x.请)

C# 获取扩展方法的属性';这是她第一次和lambda吵架?(x=>;x.请),c#,lambda,extension-methods,C#,Lambda,Extension Methods,我正在尝试这样做: var order = new BuildingOrder(); //has a Sale property var sale = order.ConfusinglyGet(() => order.Sale); //get value of order.Sale 到目前为止,我所能想到的是: public static O ConfusinglyGet<O>(this object i, Expression<Func<O>> ex

我正在尝试这样做:

var order = new BuildingOrder(); //has a Sale property
var sale = order.ConfusinglyGet(() => order.Sale); //get value of order.Sale
到目前为止,我所能想到的是:

public static O ConfusinglyGet<O>(this object i, Expression<Func<O>> expression)
{
    return expression.Compile()();
}

看起来您想要的是:

public static O ConfusinglyGet<T, O>(this T i, Expression<Func<T, O>> expression) where O : class, new()
{
    return expression.Compile()(i) ?? new O();
}
publicstatico-ConfusinglyGet(thisti,Expression-Expression),其中O:class,new()
{
返回表达式.Compile()(i)??新的O();
}

对于
表达式
,您不需要额外级别的间接寻址,因为您在示例中没有传递表达式:您传递的是一个简单的
Func

这应该适合您:

public static O FreemasonsOnly<I,O>(this I i, Func<I,O> f)
where I : class where O : class, new()
{
    return i != null ? f(i) : new O();
}
public static O freemasons only(此I I,函数f)
其中I:class其中O:class,new()
{
返回i!=null?f(i):新的O();
}

这是我的猜测,但是为什么将
i
传递给编译后的表达式会得到i的属性值呢?编译后的表达式基本上是一个具有父对象参数的
get
方法吗?编译表达式会生成一个委托,该委托(在我的示例中)接受一个T类型的实例并返回一个O类型的实例。后面的括号(i)从周围的方法传递T的实例(ConfusinglyGet)然后将O类型的结果实例返回给ConfusinglyGet的调用方。是的,我理解这一部分,但我想我想知道为什么它是这样工作的。换句话说,代表的性质是什么?它让我想起了一点
PropertyInfo.GetValue(i,null)
。它是否表示或模拟属性或其他对象的get访问器?委托是一个函数。如果你是C++程序员,它大致相当于函数指针。调用它相当于调用一个函数,该函数检索并返回有问题的属性。
public static O FreemasonsOnly<I,O>(this I i, Func<I,O> f)
where I : class where O : class, new()
{
    return i != null ? f(i) : new O();
}