如何创建 NodeType 为 ExpressionType.Index 的 .NET 表达式?
我正在编写评估 .NET Expression
树的代码。我正在尝试创建一个 C# 4 测试来练习对 ExpressionType.Index
的处理,但我不知道如何通过 LambdaExpression
创建该类型的表达式>。无论我尝试什么,表达式都会以 ExpressionType.Call
或 ExpressionType.ArrayIndex
的形式出现。例如:
IList<int> myList = new ObservableCollection<int> { 3, 56, 8 };
Expression<Func<int>> myExpression = () => myList[3];
// myExpression.Body.NodeType == ExpressionType.Call
myList = new int[] { 3, 56, 8 };
myExpression = () => myList[3];
// myExpression.Body.NodeType == ExpressionType.Call
int[] myArray = new int[] { 3, 56, 8 };
myExpression = () => myArray[3];
// myExpression.Body.NodeType == ExpressionType.ArrayIndex
List<int> myNonInterfaceList = new List<int> { 3, 7, 4, 2 };
myExpression = () => myNonInterfaceList[3];
// myExpression.Body.NodeType == ExpressionType.Call
什么是 IndexExpression
,是否可以通过 C# 4 中的内联 LambdaExpression
创建?
I'm writing code that evaluates .NET Expression
trees. I'm trying to create a C# 4 test to exercise my handling of an ExpressionType.Index
, but I can't figure out how to create that type of expression through a LambdaExpression
. No matter what I try, the expression comes out as an ExpressionType.Call
or ExpressionType.ArrayIndex
. For example:
IList<int> myList = new ObservableCollection<int> { 3, 56, 8 };
Expression<Func<int>> myExpression = () => myList[3];
// myExpression.Body.NodeType == ExpressionType.Call
myList = new int[] { 3, 56, 8 };
myExpression = () => myList[3];
// myExpression.Body.NodeType == ExpressionType.Call
int[] myArray = new int[] { 3, 56, 8 };
myExpression = () => myArray[3];
// myExpression.Body.NodeType == ExpressionType.ArrayIndex
List<int> myNonInterfaceList = new List<int> { 3, 7, 4, 2 };
myExpression = () => myNonInterfaceList[3];
// myExpression.Body.NodeType == ExpressionType.Call
What is an IndexExpression
, and can one be created through an inline LambdaExpression
in C# 4?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IndexExpression
正是您所期望的(即数组访问或索引器属性)。它是从 DLR 移植过来的众多新表达式类型之一。然而,C# 4.0 编译器使用与其先前版本相同的表达式类型,因此它不会在任何地方使用IndexExpression
。如果设计者愿意,其他语言也可以这样做。要以编程方式创建
IndexExpression
,请使用静态ArrayAccess()
、MakeIndex()
或Property()
方法在Expression
类上。An
IndexExpression
is exactly what you expect (i.e., array access or indexer property). It's one of the many new expression types that was ported over from the DLR. The C# 4.0 compiler, however, uses the same expression types as its previous version, so it won't useIndexExpression
anywhere. Other languages may do so if their designers wish it.To create an
IndexExpression
programmatically, use the staticArrayAccess()
,MakeIndex()
, orProperty()
methods on theExpression
class.