使用文字表达式lambda语法

时间:2017-04-27 22:34:27

标签: .net expression expression-trees

我寻求一种使用lambda语法获取类型索引器属性的方法。这个问题向您展示了如何使用反射来获取它:

https://stackoverflow.com/a/9716775/701346

我测试了这个解决方案并且它可以工作,但它有点太大而且很难以满足我的口味。我想这样做:

Expression<Func<Dictionary<string, string>, string>> index =
    e => e[default(string)];

对我来说,这对于索引器的访问者来说是MethodInfo,但我需要将索引器作为PropertyInfo,以便我可以将其传递给Expression.MakeIndex

我该怎么做?

1 个答案:

答案 0 :(得分:0)

只是删除了这个,但我想保留它以防万一它有所帮助。

我多么愚蠢,不要考虑使用Expression.Call代替Expression.MakeIndex

var p_formcollection = Expression.Parameter(typeof(FormCollection), nameof(FormCollection));
//helper method that does the same thing as in my OP
//I also used Dictionary<,> in my OP, but it's really a FormCollection
var indexer = ExpressionHelpers.GetMethodInfo<FormCollection, string>(e => e[default(string)]);
var collectionAccess = Expression.Call(p_formcollection, indexer, Expression.Constant(pi.PropertyInfo.Name));
相关问题