【问题标题】:Get Property Name by lambda within generic class [closed]在泛型类中通过 lambda 获取属性名称 [关闭]
【发布时间】: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&lt;Func&lt;...&gt;&gt; 是有原因的。

标签: c# generics lambda


【解决方案1】:

改变你的函数定义:

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

这是正确的用法:

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

【讨论】:

  • 就是这样,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 2019-05-16
  • 2021-12-04
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
相关资源
最近更新 更多