获取类名和属性名来自EX pression()=> MyClass.Name [英] Get class name and property name from an expression () => MyClass.Name
问题描述
这是MOT可能是重复的,但我无法找到一个合适的问题。
This is mot likely a duplicate, but I couldn't find a proper question.
我想获得MyClass.Name
从()=> MyClass.Name
。如何定义方法的参数以及如何转换前pression为一个字符串?
I want to get "MyClass.Name"
from () => MyClass.Name
. How do I define the method parameter and how do I convert the expression to a string?
推荐答案
这是一个防爆pression< Func键<字符串>>
,所以你可以有
That is an Expression<Func<string>>
, so you could have:
void Foo(Expression<Func<string>> selector) {...}
或
void Foo<T>(Expression<Func<T>> selector) {...}
不过,请注意语法 MyClass.Name
指的静态的财产;如果你想要一个的实例的属性,你可能需要的东西更像是一个防爆pression&LT; Func键&LT; MyClass的,串&GT;&GT;
- 例如
however, note that the syntax MyClass.Name
refers to a static property; if you want an instance property you might need something more like an Expression<Func<MyClass,string>>
- for example:
static void Foo<TSource, TValue>(
Expression<Func<TSource, TValue>> selector)
{
}
static void Main() {
Foo((MyClass obj) => obj.Name);
}
至于执行; 在这个简单的情况下,,我们可以预期车身
是一个 MemberEx pression
,这样:
As for implementation; in this simple case, we can expect the Body
to be a MemberExpression
, so:
static void Foo<TSource, TValue>(
Expression<Func<TSource, TValue>> selector)
{
var member = ((MemberExpression)selector.Body).Member;
Console.WriteLine(member.ReflectedType.Name + "." + member.Name);
}
然而,在一般情况下更加复杂。这也将工作,如果我们使用静态成员:
However, it is more complex in the general case. This will also work if we use the static member:
static void Foo<TValue>(
Expression<Func<TValue>> selector)
{
var member = ((MemberExpression)selector.Body).Member;
Console.WriteLine(member.ReflectedType.Name + "." + member.Name);
}
这篇关于获取类名和属性名来自EX pression()=&GT; MyClass.Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!