【问题标题】:Get a type's indexer as PropertyInfo using literal expression lambda syntax使用文字表达式 lambda 语法获取类型的索引器作为 PropertyInfo
【发布时间】:2017-04-28 06:52:37
【问题描述】:

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

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

我对该解决方案进行了测试,它确实有效,但对于我的口味来说,它有点太大而且太笨重了。我想这样做:

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

这让我得到的是索引器的 get 访问器的 MethodInfo,但我需要将索引器作为 PropertyInfo 获取,以便我可以将它传递给 Expression.MakeIndex

我该怎么办?

【问题讨论】:

    标签: .net expression expression-trees


    【解决方案1】:

    本来打算删除这个的,但我想我会保留它以防万一。

    我多么愚蠢,竟然不考虑使用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));
    

    【讨论】:

      猜你喜欢
      • 2017-03-22
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      相关资源
      最近更新 更多