如何从该属性的 getter/setter 中获取属性名称? [英] How to get property name from within getter/setter of that property?
问题描述
假设我们有如下属性
public string SomeProperty
{
get
{
var propName = "SomeProperty";
return "<" + propName + ">";
}
}
如何通过读取程序集信息本身将上述变量 propName
的值设置为属性名称?
How can I set value of the above variable propName
to be the property name by reading from the assembly information itself?
编辑
我们为什么需要这个?
我正在使用 此处 这将帮助我显示绑定属性的设计模式"值 - 通常是绑定值在设计模式下显示为空字符串.在设计模式"数据上下文类中,我想为我可能拥有的每个绑定属性返回属性名称.
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;
}
因此,从现在开始,我们在设计模式下显示绑定属性的 mocking
值要容易得多.
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!
这篇关于如何从该属性的 getter/setter 中获取属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!