4

これは私を驚かせたものであり、これがまったく可能かどうか疑問に思っています。

簡単に言うと、コードは次のとおりです。

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;
    }
(....)
}

ご覧のとおり、コードを複製しています。継承されたクラスを作成していなかったら、次のように書きます

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)
}

だから、私の質問は -baseクラスコンストラクターとコンストラクターの両方を呼び出すことができthisますか?

4

2 に答える 2

8

簡単な答え: いいえ、できません。

回避策:

public NotificationCollection() : this(Enumerable.Empty<Notification>())
{
}

public NotificationCollection(IEnumerable<Notification> items)
    : base(items)
{
    this.CollectionChanged += NotificationCollection_CollectionChanged;
    this.PropertyChanged += NotificationCollection_PropertyChanged;
}
于 2013-09-06T08:44:47.773 に答える