Expression.ArrayAccess() 在 IDictionary<string,object> 上按键名
Expression.ArrayAccess() on IDictionary<string,object> by key name
如何创建表达式树以通过数组访问读取值 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));
如果使用索引器在 class 上弹出引擎盖,则有一个 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
如何创建表达式树以通过数组访问读取值 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));
如果使用索引器在 class 上弹出引擎盖,则有一个 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