How to get MemberInfo of ArrayLength type expressions?

佐手、 提交于 2020-01-16 01:10:25

问题


Some trouble with UnaryExpressions.

This works this way:

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;

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 = ??

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

I can do it with a hack like this:

var member = (k.Body as UnaryExpression).Operand.Type.GetProperty("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?


回答1:


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

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.

EDIT: 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;

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



来源:https://stackoverflow.com/questions/19336342/how-to-get-memberinfo-of-arraylength-type-expressions

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