C# 我检查INotifyPropertyChanged,但如何使用它?
在这篇文章中,我找到了C# 我检查INotifyPropertyChanged,但如何使用它?,c#,.net,events,properties,C#,.net,Events,Properties,在这篇文章中,我找到了INotifyPropertyChanged并检查了它,但我注意到我可以在不实现INotifyPropertyChanged的情况下做同样的事情,而且我可以定义我的事件并做同样的事情 例如在 public string CustomerName { get { return this.customerNameValue; } set { if (value != this.customerNam
INotifyPropertyChanged
并检查了它,但我注意到我可以在不实现INotifyPropertyChanged的情况下做同样的事情,而且我可以定义我的事件并做同样的事情
例如在
public string CustomerName
{
get
{
return this.customerNameValue;
}
set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
NotifyPropertyChanged("CustomerName");
}
}
}
我可以放置任何字符串,它可以在没有任何验证的情况下传递,我已经做了如下类似的事情
public delegate void ChangeHandler(string item);
public class DemoCustomer2
{
// These fields hold the values for the public properties.
private Guid idValue = Guid.NewGuid();
private string customerNameValue = String.Empty;
private string phoneNumberValue = String.Empty;
public event ChangeHandler OnChange;
void CallOnChange(string item)
{
if (OnChange != null)
OnChange(item);
}
// The constructor is private to enforce the factory pattern.
private DemoCustomer2()
{
customerNameValue = "Customer";
phoneNumberValue = "(555)555-5555";
}
// This is the public factory method.
public static DemoCustomer2 CreateNewCustomer()
{
return new DemoCustomer2();
}
// This property represents an ID, suitable
// for use as a primary key in a database.
public Guid ID
{
get
{
return this.idValue;
}
}
public string CustomerName
{
get
{
return this.customerNameValue;
}
set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
CallOnChange("CustomerName");
}
}
}
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
CallOnChange("PhoneNumber");
}
}
}
}
我没有发现使用它有什么用处,但有谁能指导我这些东西是否真的有用吗?INotifyPropertyChanged的重要意义不在于实现,而在于现在框架中有一种“官方”的做事方式。所以基本上,它给了你一个承诺,如果你实现了接口,你的实现类将与所有利用它的内置和第三方组件一起工作。当您扮演自己的解决方案角色时,无法知道您的代码是否能与其他人相处融洽。实现INotifyPropertyChanged的最大好处是实现与数据绑定的标准集成。特别是,MS UI技术WPF严重依赖于数据绑定,并且对实现INotifyPropertyChanged(和INotifyCollectionChanged)的类有很好的支持。btw,依我看,将刚刚声明的字符串变量设置为“.”@abatishchev,string.Empty!=空
。虽然如果属性设置器强制不将值设置为null,这会更有意义。对!因此,INotifyPropertyChanged
只是一个公共合同,以及大量其他FCL接口。是的。MEF是同一事物的另一个例子。我以前实现过插件功能,但现在MEF是“官方”的实现方式。