本文介绍了如何获取ArrayLength类型表达式的MemberInfo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UnaryExpression遇到一些麻烦.

这可以通过以下方式起作用:

Expression<Func<List<string>, object>> k = l => l.Count;
//got member in this case like this
var member = ((k.Body as UnaryExpression).Operand as MemberExpression).Member;

在上述情况下,k.Body.NodeTypeExpressionType.Convert.但是ExpressionType.ArrayLength有点棘手. 在以下情况下,如何类似地获得PropertyInfo member?

In the above case the k.Body.NodeType was ExpressionType.Convert. But it's a little tricky with ExpressionType.ArrayLength. How would I get the PropertyInfo member similarly in the below case?:

Expression<Func<string[], int>> k = l => l.Length;
var member = ??

在第二种情况下,k.Body类似于ArrayLength(l).

In the second case k.Body is something like ArrayLength(l).

我可以用这样的hack来做到这一点:

I can do it with a hack like this:

var member = (k.Body as UnaryExpression).Operand.Type.GetProperty("Length");

,但这并不像直接表达方式.它更像是一个普通的旧反射调用,其中传递了肮脏的字符串"Length".有更好的方法吗?

but this doesn't feel like a straight forward expression approach. It's more a plain old reflection call with dirty string "Length" passed. Is there a better way?

推荐答案

这是一个ArrayLength节点,可以使用 Expression.ArrayLength 方法.

It's an ArrayLength node, which you can create with the Expression.ArrayLength method.

它只是一个UnaryExpression,其中Operand是数组表达式,而NodeTypeArrayLength.对我来说,尚不十分清楚您想知道什么,但是希望Expression.ArrayLength的调用符合您的需求.

It's just a UnaryExpression with an Operand which is the array expression, and a NodeType of ArrayLength. It's not entirely clear to me what you wanted to know about it, but hopefully the call to Expression.ArrayLength is what you were after.

尽管有 Array.Length属性,这不是通常使用的属性.例如:

Although there is an Array.Length property, that's not what's used normally. For example:

int[] x = new int[10];
Array y = x;

int a = x.Length;
int b = y.Length;

...然后评估x.Length使用ldlen IL指令,而评估y.Length使用对该属性的调用.

... then evaluating x.Length uses the ldlen IL instruction whereas evaluating y.Length uses a call to the property.

这篇关于如何获取ArrayLength类型表达式的MemberInfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 17:08