我已经看到应用程序无处不在实现此接口。在很多情况下,我们可以使用新的属性语法,如什么时候需要实现INotifyPropertyChanged?
public int Foo { get; set; }
我非常喜欢。但是,为了实现这个接口,这个接口必须变成10行左右。这使代码非常混乱,我不确定它是否也会伤害性能。
有人可以解释什么时候这个接口真的有必要吗?
我已经看到应用程序无处不在实现此接口。在很多情况下,我们可以使用新的属性语法,如什么时候需要实现INotifyPropertyChanged?
public int Foo { get; set; }
我非常喜欢。但是,为了实现这个接口,这个接口必须变成10行左右。这使代码非常混乱,我不确定它是否也会伤害性能。
有人可以解释什么时候这个接口真的有必要吗?
如果您想订阅属性已更改的通知,则必须执行此操作。如果你不需要(也没有第三方库需要),你不必实现这个接口。
当数据对象需要通告(通知)属性已更改时,您可以实现该接口。这在使用数据绑定时尤为重要,在使用Observer模式时非常有用。
Check here对于我有一个方法时,我有很多需要通知变化的属性。
在期望它的框架内使用库或其他功能时,此接口是必需的。
最常见的是使用像WPF一样的UI框架和数据绑定。为了使UI知道你的属性已经改变了,所以它可以反映TextBox的内容,例如,它的边界所需的对象或者是DependencyObject,并且该属性需要是DependencyProperty,或者你需要实现INotifyPropertyChanged。
这就是使双向数据绑定正常工作的原因。
这就是说,通常在基类上实现它,这可以使您的子类实现只有每个属性几行。 (你不能使用自动属性,但是如果你使用基类,你可能只需要一些额外的行。)
另一种方法是使用微软的ReactiveExtensions(Rx)框架来包装所有管道工作成单个可观测物体。
有关如何执行此操作的示例,请参阅this StackOverflow question and answers。
那样做
public class ViewModelBase : INotifyPropertyChanged
{
protected void SetProperty<t>(ref T newValue, ref T currentValue, bool notify, string propertyName, params string[] additionalProperties)
{
bool changed = notify && ((newValue != null && !newValue.Equals(currentValue)) || (newValue == null && currentValue != null));
currentValue = newValue;
if (changed)
{
OnPropertyChanged(propertyName);
if (additionalProperties != null)
foreach (string additionalProperty in additionalProperties)
OnPropertyChanged(additionalProperty);
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MyRealViewModel : ViewModelBase
{ 公众诠释NumberOfItems { 得到{_numItems; } {SetProperty(ref value,ref _numItems,true,“NumberOfItems”); }}
public bool SomeKindOfFlag
{
get { return _flag; }
set { SetProperty(ref value, ref _flag, false, ""); }
}
public LightSabre WeaponOfChoice
{
get { return _weapon; }
set { SetProperty(ref value, ref _weapon, true, "WeaponOfChoice", "SomeKindOfFlag", "NumberOfItems"); }
}
private bool _flag;
private int _numItems;
private LightSabre _weapon;
}
public class LightSabre
{
公共字符串LightSabreName {获得;组; }
public override bool Equals(object obj)
{
if (obj != null && obj as LightSabre != null)
return ((LightSabre)obj).LightSabreName == this.LightSabreName;
return false;
}
}
它提炼出来的上述回答,真的帮助了我。
它用于数据绑定属性通知 – 2010-10-05 00:48:27