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

This is most likely a duplicate, but I could not find the right question.

I want to get "MyClass.Name" from () => MyClass.Name . How to determine a method parameter and how to convert an expression to a string?

+3
source share
2 answers

This is Expression<Func<string>> , so you can:

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

or

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

however, note that the syntax of MyClass.Name refers to a static property; if you want an instance property, you might need something like 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 the implementation; in this simple case , we can expect that Body will be MemberExpression , therefore:

 static void Foo<TSource, TValue>( Expression<Func<TSource, TValue>> selector) { var member = ((MemberExpression)selector.Body).Member; Console.WriteLine(member.ReflectedType.Name + "." + member.Name); } 

However, in the general case, it is more complicated. This will also work if we use a static member:

 static void Foo<TValue>( Expression<Func<TValue>> selector) { var member = ((MemberExpression)selector.Body).Member; Console.WriteLine(member.ReflectedType.Name + "." + member.Name); } 
+4
source

It depends on whether Name static property.
1.If it is not static, then MyClass.Name will not be valid syntax at all. Therefore, suppose that in this case you want to get class+property from using a local variable as follows:

 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 Mark's answer.

2. The Name property may also be static, which is unlikely in my opinion, but it will allow the use of the following syntax, which is the exact syntax, as you requested:

 string result = GetClassAndPropertyName(() => MyClass.Name); 
+1
source

Source: https://habr.com/ru/post/1381155/


All Articles