Sha*_*aan 4 c# inheritance constructor
这是令我印象深刻的事情,我想知道这是否可能.
长话短说 - 这是代码:
public class NotificationCollection : ObservableCollection<Notification>
{
public NotificationCollection() : base()
{
this.CollectionChanged += NotificationCollection_CollectionChanged;
this.PropertyChanged += NotificationCollection_PropertyChanged;
}
public NotificationCollection(IEnumerable<Notification> items)
: base(items)
{
this.CollectionChanged += NotificationCollection_CollectionChanged;
this.PropertyChanged += NotificationCollection_PropertyChanged;
}
(....)
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我正在复制代码.如果我没有创建一个继承的类,我会写
public NotificationCollection(IEnumerable<Notification> items)
: this() //I can just call the empty constructor
{
//do stuff here...
//however, in case of inheritance this would be handled by base(items)
}
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是 - 我可以同时调用base
类构造函数和this
构造函数吗?
简答:不,你不能.
解决方法:
public NotificationCollection() : this(Enumerable.Empty<Notification>())
{
}
public NotificationCollection(IEnumerable<Notification> items)
: base(items)
{
this.CollectionChanged += NotificationCollection_CollectionChanged;
this.PropertyChanged += NotificationCollection_PropertyChanged;
}
Run Code Online (Sandbox Code Playgroud)
您只能链接到一个构造函数 - 在当前类型(this(...)
)或基本类型(base(...)
)中.如果你需要在这两种情况下调用不同的基础构造函数,那么不 - 你不能共享this()
代码.但是,您可以将该代码移动到单独的方法中,并从两个位置调用它(假设不readonly
涉及成员).
但是,您也应该不想订阅自己的活动 - 这通常是代码味道.在这种情况下,最好检查一下override
:
public class NotificationCollection : ObservableCollection<Notification>
{
public NotificationCollection() : base() {}
public NotificationCollection(IEnumerable<Notification> items)
: base(items) {}
protected override void OnCollectionChanged(
NotifyCollectionChangedEventArgs e)
{
// YOUR CODE HERE
base.OnCollectionChanged(e);
}
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
// YOUR CODE HERE
base.OnPropertyChanged(e);
}
}
Run Code Online (Sandbox Code Playgroud)