这只是我在学习属性时想到的事情,而且我太多地使用了 INotifyPropertyChanged,这只是一个想法,我想听听一些关于它的意见。(我知道这需要在编译器上做一些工作,而不是在消费者方面)
由于 INotifyPropertyChanged 大多数时候都与相同的模式一起使用..就像调用使用属性名称触发事件的方法一样,是否可以将其设计为属性并使用自动属性?这样编译器就知道需要添加对 PropertyChanged 事件的调用吗?
所以如果我们有课的话......
public class DemoCustomer : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private string companyNameValue = String.Empty;
...
}
而不是申报财产
public string CompanyName
{
get
{
return this.companyNameValue;
}
set
{
if (value != this.companyNameValue)
{
this.companyNameValue = value;
NotifyPropertyChanged("CompanyName");
}
}
}
如果我们可以通过此属性向编译器指示,如果新值与之前的值不同,则需要使用属性名称生成对 PropertyChanged 的调用,那么我们可以执行类似的操作
[NotifyPropertyChanged]
public string CompanyName
{
get;set;
}
当不使用属性时,我们仍然可以以旧的方式对某些自定义行为进行编码。
如果有人遇到此线程并且正在使用 C# 5(VS 2012+、.NET 4.5+)。这种情况现在可以“更容易”完成CallerMemberNameAttribute
。此属性应用于字符串参数,并导致编译器在使用默认值时(即未传递参数时)传递调用方法/属性的名称。制定实施INotifyPropertyChanged
不那么无聊。例如:
public class MyClass
{
private string myProperty;
public string MyProperty
{
get { return myProperty; }
set
{
myProperty = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
所以,你只需要OnPropertyChanged()
在每个 setter 中发送事件,而不必处理属性名称的硬编码字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)