要么,如果你想公开为ICollection<IType>
,从而使外部呼叫者添加ITypes
不在MyTypes
声明this.items
为List<IType>
。
这样的内部工作,对列表中的项目
var myObj = this.items[i] as MyType;
if (myObj == null) {
work with this.items[i] and treat it as a IType
} else {
work with myObj which is a MyType
}
OR
声明公共财产
public ICollection<MyType> Items { get return this.items; } }
,从而允许外部呼叫者添加MyType
类型的唯一项目。
我很抱歉,但你不能满足条件(2)和(3)在同一时间
UPDATE
另一种选择是只允许外部呼叫者获得的物品该列表但不添加项目,通过使用只有一个getter的索引器。
public IType this[int i]
{
get { return this.items[i]; }
}
外部呼叫者可再接入的项目,如本
var obj = new ClassImplementingThisStuff();
int i = 5;
IType x = obj[i];
另外添加计数属性
public int Count {
get { return this items.Count; }
}
这种解决方案避免了不必要的枚举。
要求(2)和(3)是矛盾的。你不知道调用者要添加到集合中的具体类型,那么你怎样才能把它们作为一种特定的类型来对待呢? –
如果你期望项目是特定类型的,允许外部类添加项目是危险的 - 当你将它们全部视为猫时,你不会希望有人为你的动物集合添加一条狗:-) – Cameron
@PaulPhillips - 这是一个好点。我可能需要重新考虑这是如何设计的。 –