IDictionary< string,object>上的Expression.ArrayAccess()按键名 [英] Expression.ArrayAccess() on IDictionary<string,object> by key name

查看:56
本文介绍了IDictionary< string,object>上的Expression.ArrayAccess()按键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建表达式树以通过数组访问IDictionary<string,object>来读取值?

How do I create expression tree for reading a value by array access for an IDictionary<string,object>?

我想代表:

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

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

I can't find any example of ArrayAccess being used to access with string name. I want something like:

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

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

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

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

I get error stating it is not an array. What is correct way to do this?

推荐答案

可能* 想要访问属性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属性.考虑以下示例:

If you pop the hood on a class with an indexer, there is an Item property. Consider this example:

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

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

has the following (relevant to indexers) 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

这篇关于IDictionary&lt; string,object&gt;上的Expression.ArrayAccess()按键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆