对象中初始化一个集合? [英] Initialize a collection within an object?

查看:201
本文介绍了对象中初始化一个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个对象有一个属性,它是一个集合,如果对象创建集合对象或让消费者检查空?我知道,消费者不应该假定,只是想知道,大多数人创建集合对象,如果它永远不会加入。

If an object has a property that is a collection, should the object create the collection object or make a consumer check for null? I know the consumer should not assume, just wondering if most people create the collection object if it is never added to.

推荐答案

您也可以使用那里的集合直到(除非)初始化懒initailizer的格局有人访问属性getter吧...这可避免在父对象被实例化用于其他目的的那些情况下,创造它的开销,不需要在收集...

You can also use the "Lazy initailizer" pattern where the collection is not initialized until (and unless) someone accesses the property getter for it... This avoids the overhead of creating it in those cases where the parent object is instantiated for some other purpose that does not require the collection...

   public class Division
    {
        private int divId;
        public int DivisionId { get; set; }

        private Collection<Employee> emps;
        public Collection<Employee> Employees
        { get {return emps?? (emps = new Collection<Employee>(DivisionId));}} 
    }

编辑:此实现图案,在一般情况下,不是线程安全...的em​​ps可以由两个不同的线程被读作零之前第一线程完修改它。在这种情况下,可能并不重要作为DivisionId是不可改变的,尽管这两个线程会得到不同的集合,它们将都是有效的。 Whne第二螺纹fihishes,因此,的emps将是一个有效的收集。在可能,是因为它是可能的第一线,以开始使用环境管理计划之前,第二个线程重置它。这不会是线程安全的。另一个稍微复杂的实现从乔恩斯基特是线程安全的(见本文对单身有关如何解决这一问题他为榜样/讨论。

This implementation pattern is, in general, not thread safe... emps could be read by two different threads as null before first thread finishes modifying it. In this case, it probably does not matter as DivisionId is immutable and although both threads would get different collections, they would both be valid. Whne the second thread fihishes, therefore, emps would be a valid collection. The 'probably' is because it might be possible for the first thread to start using emps before the second thread resets it. That would not be thread-safe. Another slightly more complex implementation from Jon SKeet is thread-safe (see This article on SIngletons for his example/discussion on how to fix this.

这篇关于对象中初始化一个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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