从ObservableCollection继承的Collection-有什么好处? [英] Collection that inherits from ObservableCollection - What are the benefits?

查看:37
本文介绍了从ObservableCollection继承的Collection-有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看了此MSDN文章之后,我现在想知道的是好处(如果有的话)是将集合定义为继承自 ObservableCollection 的类.两者之间有什么显着区别吗?

After looking at this MSDN article, I am now wondering what the benefit, if any, is of defining a collection as a class that inherits from ObservableCollection. Are there any significant differences between this:

class MyCollection : ObservableCollection<MyObject> { }

class Class1
{
    private MyCollection _newCollection = new MyCollection();

    public Class1()
    {
        _newCollection.Add(new MyObject());
    }
}

和这个:

class Class1
{
    private ObservableCollection<MyObject> _newCollection = new ObservableCollection<MyObject>();

    public Class1()
    {
        _newCollection.Add(new MyObject());
    }
}

这里有什么我可以俯瞰的地方吗?

Is there something I'm overlooking here?

推荐答案

一个主要好处是您可以定义 Add 函数,这使内联初始化更加容易.因此,例如:

One major benefit is that you can define the Add function, which makes inline initialization easier. So for example this:

class MyCollection : ObservableCollection<MyObject> 
{  
    public void Add(string prop1, string prop2)
    {
        base.Add(new MyObject { Prop1 = prop1, Prop2 = prop2 });
    }
}

让你这样写:

MyCollection collection = new MyCollection
{
    { "prop1", "prop2" },
    { "prop1", "prop2" },
};

第二个(相关的)好处:如果您正在使用XAML,拥有一个子类化的集合可让您将集合实例(用于设计/测试用例)定义为标记,如下所示:

A second (related) benefit: if you're working with XAML, having a subclassed collection lets you define collection instances (for design/test cases) as markup, as in:

<local:MyCollection xmlns:local="MyNamespace">
    <local:MyObject Prop1="prop1" Prop2="prop2" />
    <local:MyObject Prop1="prop1" Prop2="prop2" />
</local>

最后,(我想这只是一个口味问题),它总体上不会受到伤害,并且可以提供帮助.有时,对于给定的集合类型,您最终需要更多的方法/属性.准备好一个类型化的子类,而无需重构很高兴.

Lastly, (and this is merely a matter of taste, I suppose) it doesn't hurt in general, and can help. Sometimes you end up needing more methods/properties for a given collection type. It's nice to have a typed subclass ready, without needing to refactor.

这篇关于从ObservableCollection继承的Collection-有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆