问题描述
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.NodeType
是ExpressionType.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
是数组表达式,而NodeType
是ArrayLength
.对我来说,尚不十分清楚您想知道什么,但是希望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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!