反映动态功能

时间:2015-01-12 15:26:56

标签: c# dynamic reflection inspect

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

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

这可能吗?如果是这样,如果解决方案是基于反射的(因为我认为它必须是),那么会有很大的性能影响吗?

1 个答案:

答案 0 :(得分:1)

您必须使用经典的“审讯”方法Func<..> - Retrieving Property name from lambda expression

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