开发者

Get class name and property name from an expression () => MyClass.Name

开发者 https://www.devze.com 2023-02-11 15:51 出处:网络
This is mot likely a duplicate, but I couldn\'t find a proper question. I want to get \"MyCla开发者_如何学编程ss.Name\" from () => MyClass.Name. How do I define the method parameter and how do I c

This is mot likely a duplicate, but I couldn't find a proper question.

I want to get "MyCla开发者_如何学编程ss.Name" from () => MyClass.Name. How do I define the method parameter and how do I convert the expression to a string?


That is an Expression<Func<string>>, so you could have:

void Foo(Expression<Func<string>> selector) {...}

or

void Foo<T>(Expression<Func<T>> selector) {...}

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);        
}

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);
}


It depends on whether Name is static property.
1.If it is not static then MyClass.Name will not be a valid syntax at all. So let's assume that in this case you want to get class+property from local variable usage like this:

var instance = new MyClass();
string result = GetClassAndPropertyName(() => instance.Name);

So the implementation for GetClassAndPropertyName should be like this:

public static string GetClassAndPropertyName<T>(Expression<Func<T>> e)
{
    MemberExpression memberExpression = (MemberExpression) e.Body;
    return memberExpression.Member.DeclaringType.Name + "." + memberExpression.Member.Name;
}

Another syntax you can find in Marc's answer.

2.Name property could also be static, which is unlikely on my opinion, but it will allow following syntax, which is exact syntax as you have asked for:

string result = GetClassAndPropertyName(() => MyClass.Name);
0

精彩评论

暂无评论...
验证码 换一张
取 消