来自 PropertyInfo,c#,linq,system.reflection,propertyinfo"/>

首页 > 解决方案 > 获取功能来自 PropertyInfo

问题描述

我遇到了以下问题:
我有一个像

public class DataItem
{
    public decimal? ValueA{ get; set; }
    public decimal? ValueB { get; set; }
    public decimal? valueC { get; set; }
    ...
}

并想拥有类似的东西

 var keySelectors = new Dictionary<string, Func<DataItem, decimal?>>
 {
     {"ValueA", x => x.ValueA},
     {"ValueB", x => x.ValueB},
     {"ValueC", x => x.ValueC},
     ...
 }.ToList();

用于用户定义的分析,但我需要一种更通用的方法来创建它。
所以我尝试了以下方法:

var keySelectors= typeof(DataItem).GetProperties()
  .Select(x => new KeyValuePair<string, Func<DataItem, decimal?>>(x.Name, x.DoNotKnow));

DoNotKnow是我迷路的地方。

或者,对于期望的结果,使用户能够选择他的分析所基于的数据,这是一种错误的方法吗?

标签: c#linqsystem.reflectionpropertyinfo

解决方案


您要做的是创建一个实例方法的委托,即属性的 getter 方法。这可以通过 CreateDelegate 来完成:

var props = typeof(DataItem).GetProperties()
    .Select(x => new KeyValuePair<string, Func<DataItem, decimal?>>(x.Name,
     (Func<DataItem, decimal?>)x.GetGetMethod().CreateDelegate(typeof(Func<DataItem, decimal?>))));

调用委托比使用基于反射的方法 GetValue on PropertyInfo 更快,但显然影响取决于您的方案。


推荐阅读