How does one create a .NET Expression with NodeType of ExpressionType.Index?

谁说我不能喝 提交于 2019-12-07 15:17:24

问题


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?


回答1:


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 use IndexExpression anywhere. Other languages may do so if their designers wish it.

To create an IndexExpression programmatically, use the static ArrayAccess(),MakeIndex(), or Property() methods on the Expression class.



来源:https://stackoverflow.com/questions/3340500/how-does-one-create-a-net-expression-with-nodetype-of-expressiontype-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!