反映动态功能

本文关键字:功能 动态 | 更新日期: 2023-09-27 18:37:17

我创建了一个检查对象并返回一组[请求]属性的方法。

public static List<object> Inspect<T>(T obj, params Func<T, object>[] funcs)
{
   List<object> results = new List<object>(funcs.Length);
   foreach (var func in funcs)
   {
      results.Add(func(obj));
   }
   return results;
}

然后调用它,例如在List上,如下所示:

List<string> peopleData = new List<string>(10) { "name", "age", "address" };
List<object> properties = Inspect(peopleData, p => p.Count, p => p.Capacity);
// The results would be
// properties[0] = 3
// properties[1] = 10

我想调整 Inspect 方法以返回一个 Dictionary<string, object> ,其中字典的键将是属性名称。然后,将像这样调用适应的方法:

List<string> peopleData = new List<string>(10) { "name", "age", "address" };
Dictionary<string, object> properties = Inspect(peopleData, p => p.Count, p => p.Capacity);
// The results would be
// properties["Count"] = 3
// properties["Capacity"] = 10

这可能吗?如果是这样,并且如果解决方案是基于反射的(我认为它必须是),是否会对性能造成很大影响?

反映动态功能

您必须使用经典的"审讯"方法来Func<..> - 从 lambda 表达式中检索属性名称

public static IDictionary<string, object> Inspect<T>(T obj, 
     params Expression<Func<T, object>>[] funcs)
{
   Dictionary<string, object> results = new Dictionary<string, object>();
   foreach (var func in funcs)
   {
      var propInfo = GetPropertyInfo(obj, func)
      results[propInfo.Name] = func.Compile()(obj));
   }
   return results;
}

Ps,正如 Servy 指出的那样,您还需要使参数使用 Expression .