How to get a property name from the property of a

2019-06-14 19:02发布

问题:

This question already has an answer here:

  • Get name of property as a string 13 answers
  • How to raise PropertyChanged event without using string name 8 answers

This is the kind of code I'd like to make work:

string Name = GetPropName(myClass.SomeProperty); // returns "SomeProperty"

Because I might be renaming my class' properties, I wouldn't like to forget to change their string names somewhere in my code, and there are quite a few places I use string names for properties, so I'd like to have this handy method to get the current name of a property as string for me. How do I do this?

What I'm after is a method that returns only the string name of the property it receives as a parameter.

I see there have been similar questions asked before, but there are no answers that explain well how to do what I'm trying to do.

回答1:

The problem with calling the method and passing in MyClass.MyProperty is that the value of the property is sent to the method. You can try and use reflection to get the property name from that value, but there are two issues with that:

1 - The property needs to have a value.

2 - If two properties of the same type have the same values, there's no way (at least as far as I know) to differentiate the two.

What you could do though is use an Expression to pass the property into the method, get the body of that expression and finally the member (property) name:

 public static string GetPropertyName<T, P>(Expression<Func<T, P>> propertyDelegate)
 {
     var expression = (MemberExpression)propertyDelegate.Body;
     return expression.Member.Name;
 }

And to use it:

string myPropertyName = GetPropertyName((MyClass x) => x.SomeProperty);