【发布时间】:2018-02-16 15:26:59
【问题描述】:
这是我的通用 Container 类:
public class Container<T> : IContainer<T> where T : BaseModel, new()
{
private string include;
public Container()
{
}
public Container<T> Include(Expression<Func<T>> property)
{
include = GetMemberName(property);
return this;
}
}
现在我想像这样设置包含值:
var container = new Container<TestClass>();
// doesn't work
container.Include(x => x.SomeProperty);
// also doesn't work
container.Include(() => TestClass.SomeProperty);
因此include 应该具有SomeValue 的值。我还尝试了一个无参数函数,在后一种情况下,VS 说它缺少非静态属性的对象引用。
我从这个线程获得了 GetMemberName:[Retrieving Property name from lambda expression
【问题讨论】:
-
我建议您也阅读该线程的其余部分,它包含您需要的所有信息。
-
请注意,您链接到的答案有第二个参数
Expression<Func<...>>是有原因的。