如何创建表达式树,通过数组访问来读取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);我在声明它不是数组时出错。怎样做才是正确的呢?
发布于 2015-05-03 02:29:11
*想要访问属性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_Itemhttps://stackoverflow.com/questions/30009512
复制相似问题