c# - 获取功能来自 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是我迷路的地方。
或者,对于期望的结果,使用户能够选择他的分析所基于的数据,这是一种错误的方法吗?
解决方案
您要做的是创建一个实例方法的委托,即属性的 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 更快,但显然影响取决于您的方案。
推荐阅读
- entity-framework-core - 给定主键,是否可以在 EF Core 模型中找到所有外键?
- php - 未知深度多维数组上的PHP foreach循环
- laravel - Laravel 5.8 护照注销方法(未验证)
- java - 如何阻止在货币之前生成?
- c# - 如何使用 asp.net (htmlpackagility) 抓取特定类
- python-3.x - 数组的子数组的所有 mex 的总和
- django - django 中的用户身份验证:使用 api 而不是表单登录
- android - Kotlin Android - 更改剪切/复制/粘贴文本颜色
- java - 使用 Apache Commons Configuration 2.5 从 xml 文件读取地图的最优雅方法是什么?
- python - 通过比较文件 2 的所有行与文件 1 的每一行来读取两个文件