我想得到一个给定属性的字符串表示。这样,我可以使用这个字符串,NotifyPropertyChanged
并且在重构属性名称后仍然可以。
编辑:我正在使用 .NET 4.0
更新:我还想为DependencyProprty
s 提供名称,即我需要在静态变量赋值期间使用该值。
相同的示例代码来解释:
// actual code
private int prop = 42;
public int Prop
{
get
{
return prop;
}
set
{
prop = value;
NotifyPropertyChanged("Prop"); // I'd like to replace the hard-coded string here
}
}
// code as I'd like it to be
private int propNew = 42;
private static readonly string PropNewName = GainStringFromPropertySomeHow(PropNew); // should be "PropNew"
public int PropNew
{
get
{
return propNew;
}
set
{
propNew = value;
NotifyPropertyChanged(PropNewName); // <== will remain correct even if PropNew name is changed
}
}
重构后:
private int prop = 42;
public int PropNameChanged
{
get
{
return prop;
}
set
{
prop = value;
NotifyPropertyChanged("Prop"); // oops
}
}
private int propNew = 42;
private static readonly string PropNewName = GainStringFromPropertySomeHow(PropNewNameChanged); // should be "PropNewNameChanged"
public int PropNewNameChanged
{
get
{
return propNew;
}
set
{
propNew = value;
NotifyPropertyChanged(PropNewName); // still correct
}
}