开发者

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

开发者 https://www.devze.com 2023-01-09 04:20 出处:网络
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 creat开发者_开发知识库e that

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 creat开发者_开发知识库e 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消