How to get property name from within getter/setter of that property? [duplicate]
Let's say we have a property as below
public string SomeProperty
{
get
{
var propName = "SomeProperty";
return "<" + propName + ">";
}
}
How can I set value of the above variable propName
to be the property name by reading from the assembly information itself?
Edit
Why we need this?
I'm using the WPF d:DataContext
as mentioned in here which will help me to display a 'design-mode' value for bound properties - very often, the bound values are displayed as empty string in design mode. And in the 'design-mode' data-context class, I want to return the property name for every binding properties I may have.
Hope this would explain your concerns.
After a while I figure out a solution as below, which is quite convenient to me.
string SomeProperty
{
get
{
return GetDesignModeValue(() => this.SomeProperty);
}
}
string GetDesignModeValue<T>(Expression<Func<T>> propertyExpression)
{
var propName = (propertyExpression.Body as MemberExpression).Member.Name;
var value = string.Format(
"<{0}>"
, propName);
return value;
}
So, from now on, it is much much easier for us to show the binding properties' mocking
value when in design mode.
I hope you would find it helpful somedays!
There isn't a reliable way for doing that at runtime, but you can use MethodBase.GetCurrentMethod().Name
and throw away the first four characters.
This approach has some flaws: running the binary through an obfuscation tool may cause the method to get renamed. Additionally, the method may be inlined and cause problems (if you just use Remove
on the string without checking the length, it may even cause unexpected crashes in the Release build that can be difficult to reproduce in Debug mode).
If your code follows a pattern and you need to generate a bunch of properties like that, it's better to use a compile-time approach like a code generator or an aspect-oriented programming framework.
this should also work BUT i am not sure why you require this
public string SomeProperty
{
get
{
StackTrace st = new StackTrace();
StackFrame[] fr = st.GetFrames();
if (fr != null)
{
var propName = fr[0].GetMethod().Name.Substring(3, fr[0].GetMethod().Name.Length);
return "<" + propName + ">";
}
return "SomeProperty";
}
}
It's possible to pass the name of the property to the getter.
if MyObj is the object and if PropName is the variable holding the name of the property, then the following code is doing the job:
eval("Object.defineProperty(MyObj, PropName, { " +
"get : function() { return(\"the prop name is " + PropName + "\"); } });");
精彩评论