Get the name of a property by passing it to a method

StackOverflow user jolson had a very nice piece of code that illustrates how mantodes can be registered without using strings, but expression trees are here .

Is it possible to have something similar for properties instead of methods? To pass a property (not a property name) and get a property name inside a method?

Something like that:

RegisterMethod(p => p.Name) void RegisterMethod(Expression??? propertyExpression) where T : Property ??? { string propName = propertyExpression.Name; } 

Thanks.

+4
source share
2 answers

You can write something about this:

 static void RegisterMethod<TSelf, TProp> (Expression<Func<TSelf, TProp>> expression) { var member_expression = expression.Body as MemberExpression; if (member_expression == null) return; var member = member_expression.Member; if (member.MemberType != MemberTypes.Property) return; var property = member as PropertyInfo; var name = property.Name; // ... } 
+6
source

I have posted a complete example of this here (see also the post on " this " under it)

Please note that it deals with LambdaExpression , etc. As an update to the code published, you can add a little more to make it easier to use in some scenarios:

 static class MemberUtil<TType> { public static string MemberName<TResult>(Expression<Func<TType, TResult>> member) { return MemberUtil.MemberName<TType, TResult>(member); } } 

Then you can use generic output type for the return value:

 string test1 = MemberUtil<Foo>.MemberName(x => x.Bar); string test2 = MemberUtil<Foo>.MemberName(x => x.Bloop()); 
+7
source

All Articles