简体   繁体   English

如何从表达式中获取字段名称?

[英]How can I get the name of the field from an expression?

I have an expression, passed to a function, that looks something like this: 我有一个传递给函数的表达式,看起来像这样:

x=>x.SomeField

I want somehow to get to the name of this field, the "SomeField", to be accessible for me as a string. 我想以某种方式获取该字段的名称“ SomeField”,以字符串形式供我使用。 I realize that it's possible to call myExpression.ToString(), and then parse the string, but I want a more solid, faster approach. 我意识到可以调用myExpression.ToString(),然后解析字符串,但是我想要一个更可靠,更快速的方法。

public string GetMemberName<T>(Expression<Func<T>> expr)
{
    var memberExpr = expr.Body as MemberExpression;
    if (memberExpr == null)
        throw new ArgumentException("Expression body must be a MemberExpression");
    return memberExpr.Member.Name;
}

...

MyClass x = /* whatever */;
string name = GetMemberName(() => x.Something); // returns "Something"

You have to implement a expression tree visitor 您必须实现一个表达式树访问者

http://msdn.microsoft.com/en-us/library/bb882521(VS.90).aspx http://msdn.microsoft.com/zh-CN/library/bb882521(VS.90).aspx

You put your eval code in the MemberAccessExpression visit 您将评估代码放入MemberAccessExpression访问中

I've used some of the helpers available in the ncommon framework to accomplish this. 我使用了ncommon框架中提供的一些帮助程序来完成此任务。 Specifically, you'd be interested in the classes in the Expressions namespace 具体来说,您可能会对Expressions命名空间中的类感兴趣

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM