我想獲得給定屬性的字符串表示。這樣我可以使用這個字符串NotifyPropertyChanged
,並且在重構屬性名稱後仍然可以。C#中有一種方法可以將屬性轉換爲包含名稱的字符串嗎?
編輯:我使用.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
}
}
將是一個不錯解決方案,但我使用.NET 4.0。 – Onur