If you already have a PropertyInfo
, then @dtb's answer is the right one. If, however, you're wanting to find out which property's code you're currently in, you'll have to traverse the current call stack to find out which method you're currently executing and derive the property name from there.
var stackTrace = new StackTrace();
var frames = stackTrace.GetFrames();
var thisFrame = frames[0];
var method = thisFrame.GetMethod();
var methodName = method.Name; // Should be get_* or set_*
var propertyName = method.Name.Substring(4);
Edit:
After your clarification, I'm wondering if what you're wanting to do is get the name of a property from a property expression. If so, you might want to write a method like this:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
To use it, you'd write something like this:
var propertyName = GetPropertyName(
() => myObject.AProperty); // returns "AProperty"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…