C#和属性更改通知

时间:2014-04-18 20:54:35

标签: c#

为什么C#让我这样做:

public class SomeClass {
    public event PropertyChangedEventHandler Changed;
    public void OnChanged(object sender, PropertyChangedEventArgs e)
    {
        if (Changed != null)
            Changed(sender, e);
    }

    [XmlIgnore]
    private string _name;
    public string Name { 
        get { return _name; } 
        set 
        { 
            _name = value; 
            OnChanged(this, new PropertyChangedEventArgs("Name")); 
        }
    }
}

这样的事情:

[GeneratesChangeNotifications]
public class SomeClass {
    [GeneratesChangeNotification] 
    public string Name { get; set; }
}  

我知道你可以使用PostSharp和其他第三方库做到这一点......但是我认为,某些内容如此完整且容易出错(例如拼写错误的字符串中的名称)应该被内置到语言中...为什么微软不会这样做吗?...有一些纯粹的语言原因导致这种情况不会发生。这是一个很普遍的需求。

2 个答案:

答案 0 :(得分:0)

我的RaisePropertyChanged始终使用调用者成员名称,或者如果需要,则反映在表达式中传入的属性名称(即,如果我需要为另一个属性通知一个属性)。您不能总是保证所有属性都能通知,因此能够一次通知多个属性。

此外,使用标准模型,使用事件允许任何人订阅,而属性模型不能订阅。

答案 1 :(得分:0)

到目前为止,这是我提出的最好的...我已经编写了一个名为NotifyPropertyChanged的类...它处理属性名称,测试是否已更改或不,局部变量的更新,以及更改的通知......和SetProperty函数是通用的,因此一个函数将适用于所有类型的属性...工作得很好。

(另请注意,如果您愿意,可以使用多个属性名称调用OnPropertyChanged。)

public class NotifyPropertyChanged : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(params string[] props)
    {
        foreach (var prop in props)
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
    }

    public bool SetProperty<T>(ref T oldValue, T newValue, [CallerMemberName]string prop = "")
    {
        if (oldValue == null && newValue == null)
            return false;
        if (oldValue != null && oldValue.Equals(newValue))
            return false;
        oldValue = newValue;
        OnPropertyChanged(prop);
        return true;
    }
}

然后像这样使用它:

public class MyClass : NotifyPropertyChanged
{
    public string Text { get => _text; set => SetProperty(ref _text, value); }
    string _text;
}
相关问题