如何创建表达式树以通过数组访问读取值 IDictionary<string,object>
?
我要代表:
((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);
我收到错误提示它不是一个数组。执行此操作的正确方法是什么?
最佳答案
你 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
关于c# - IDictionary<string,object> 上的 Expression.ArrayAccess() 按键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009512/