【发布时间】:2016-05-09 08:21:50
【问题描述】:
我是advised 将List<string> 属性更改为Collection<string>,在一个基类中,因为它更适合继承。
此“规则”被引用:https://msdn.microsoft.com/en-us/library/ms182142.aspx
System.Collections.Generic.List 是一个通用集合,它是 专为性能而不是继承而设计。 System.Collections.Generic.List 不包含虚拟成员 这使得更容易改变继承类的行为。这 以下泛型集合是为继承而设计的,应该 被公开而不是 System.Collections.Generic.List。
System.Collections.ObjectModel.Collection<T> System.Collections.ObjectModel.ReadOnlyCollection<T> System.Collections.ObjectModel.KeyedCollection<TKey, TItem>
类似的规则是否适用于Dictionary<string, string>?
我问是因为它也在 System.Collections.Generic 命名空间中。或者我理解错了,这条规则只适用于Lists。
顺便说一句,Dictionary 的目的是保存错误(格式与 ModelState 类似)。我目前不确定我将在哪个阶段添加错误。
如果我应该在基类中避免Dictionary<string, string>,我应该使用什么来代替它?
我遇到过KeyedCollection,但不确定这是否是一个好的替代品。
【问题讨论】:
-
等一下。你到底想达到什么目的?您是想从集合继承还是只是想将列表/字典用作基类中的属性/字段?
-
这是一个用于保存错误的属性(与 ModelState 错误的格式相似)。我目前不确定我将在哪个阶段将错误添加到字典中。
标签: c# list generics inheritance dictionary