【问题标题】:Expression.ArrayAccess() on IDictionary<string,object> by key nameIDictionary<string,object> 上的 Expression.ArrayAccess() 按键名
【发布时间】:2015-05-03 02:06:29
【问题描述】:

如何创建表达式树以通过数组访问读取 IDictionary&lt;string,object&gt; 的值?

我要代表:

((IDictionary<string,object>)T)["KeyName"]

我找不到任何用于使用字符串名称访问的 ArrayAccess 示例。我想要类似的东西:

var parameterExpression = Expression.Parameter(typeof(IDictionary<string, object>));

var paramIndex = Expression.Constant("KeyName");

var arrayAccess = Expression.ArrayAccess(parameterExpression, paramIndex);

我收到错误消息,指出它不是数组。这样做的正确方法是什么?

【问题讨论】:

  • 表达式不是数组,而是字典。您应该调用字典对象的索引器属性(“Item”)

标签: c# linq reflection lambda


【解决方案1】:

probably*想访问属性Item

var dic = new Dictionary<string, object> {
    {"KeyName", 1}
};
var parameterExpression = Expression.Parameter(typeof (IDictionary<string, object>), "d");
var constant = Expression.Constant("KeyName");
var propertyGetter = Expression.Property(parameterExpression, "Item", constant);

var expr = Expression.Lambda<Func<IDictionary<string, object>, object>>(propertyGetter, parameterExpression).Compile();

Console.WriteLine(expr(dic));

如果您使用索引器弹出类的引擎盖,则会出现Item 属性。考虑这个例子:

class HasIndexer {
    public object this[int index] {
        get { return null; }
    }
}

具有以下(与索引器相关)IL:

.property instance object Item(
    int32 index
)
{
    .get instance object ConsoleApplication8.HasIndexer::get_Item(int32)
}

.method public hidebysig specialname 
    instance object get_Item (
        int32 index
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 2 (0x2)
    .maxstack 8

    IL_0000: ldnull
    IL_0001: ret
} // end of method HasIndexer::get_Item

【讨论】:

  • 谢谢,你弥补了我的理解差距。
猜你喜欢
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
相关资源
最近更新 更多