使用表达式树使用索引器访问类型的元素 [英] Accessing elements of types with indexers using expression trees

查看:89
本文介绍了使用表达式树使用索引器访问类型的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的类型:

Suppose I have a type like this:

class Context
{
    SomeType[] Items { get; set; }
}

我希望能够使用表达式树访问特定的Items元素.假设我需要索引为0的元素.我可以按照以下方式进行操作,一切按预期进行:

I want to be able to access specific Items elements using expression trees. Suppose I need an element at index 0. I can do it like below, where everything works as expected:

var type = typeof (Context);
var param = Expression.Parameter(typeof (object));
var ctxExpr= Expression.Convert(param, context);    
var proInfo = type.GetProperty("Items");

Expression.ArrayIndex(Expression.Property(ctxExpr, proInfo), Expression.Constant(0));

如果我更改上下文类型以包含.NET提供的List<SomeType>,而不是array,即

If I change the context type to contain .NET provided List<SomeType>, instead of array, i.e.

class Context
{
    List<SomeType> Items { get; set; }
}

相同的表达式导致以下错误:

the same expression results in following error:

System.ArgumentException:参数必须是数组,位于 System.Linq.Expressions.Expression.ArrayIndex(表达式数组, 表达指数)

System.ArgumentException: Argument must be array at System.Linq.Expressions.Expression.ArrayIndex(Expression array, Expression index)

我的问题是,如何编写可以访问适当索引为List<>或更好的任何声明索引器的集合的表达式?例如.有没有什么方法可以使用表达式树检测并将此类集合转换为适当类型的array?

My question is, how to write respective expression which can access an item under appropriate index of List<>, or better - of any collection declaring indexer? E.g. is there is some way to detect, and convert such a collection to an array of appropriate types using expression trees?

推荐答案

索引器实际上只是具有附加参数的属性,因此您需要:

An indexer is really just a property with an extra parameter, so you want:

var property = Expression.Property(ctxExpr, proInfo);
var indexed = Expression.Property(property, "Item", Expression.Constant(0));

其中"Item"索引属性在这里.

(如果您事先不知道属性的名称,通常是 Item,但是您始终可以通过反射来查找它,方法是查找所有带有索引器参数的属性.)

(If you don't know the name of the property beforehand, it's usually Item but you can always find it via reflection, by finding all properties with indexer parameters.)

这篇关于使用表达式树使用索引器访问类型的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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