【发布时间】:2019-10-01 12:16:03
【问题描述】:
我想知道在必须引发PropertyChanged 事件时如何简化属性的使用。我的意思是,只要您需要引发事件,setter 就必须这样做,因此该属性不能是自动属性。这会导致代码变得复杂,尤其是当涉及多个属性时,除了简单地引发事件之外别无其他目的:
protected FlowDocument document;
protected bool hyphenation = true;
protected bool optimalParagraphs = true;
public event PropertyChangedEventHandler PropertyChanged;
public FlowDocument Document { get => document; set { document = value; RaisePropertyChanged (); } }
public bool Hyphenation { get => hyphenation; set { hyphenation = value; RaisePropertyChanged (); } }
public bool OptimalParagraphs { get => optimalParagraphs; set { optimalParagraphs = value; RaisePropertyChanged (); } }
// Raise event
protected void RaisePropertyChanged ([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName));
}
复杂性在于每个属性都重复的这部分:
protected FlowDocument document;
public FlowDocument Document { get => document; set { document = value; RaisePropertyChanged (); } }
因为不可能这样表达:
public FlowDocument Document { get; setAndRaiseEvent; }
在网站上的搜索提出了这个类似但不重复的问题:
对于当前的 C# 可能性,有没有办法简化原始代码? (我将范围扩大到任何可能性)。
【问题讨论】:
标签: c# properties inotifypropertychanged