在泛型类中获取lambda的属性名称

时间:2018-02-16 15:26:59

标签: c# generics lambda

这是我的通用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;
    }
}

现在我想设置这样的include值:

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

1 个答案:

答案 0 :(得分:1)

更改您的func定义:

public Container<T> Include(Expression<Func<T, object>> property)
{            
    include = GetMemberName(property);
    return this;
}

这是正确的用法:

container.Include(x => x.SomeProperty);