Ant*_*ean 2 .net generics constructor interface robustness
Krzysztof的建议是否适用于构造函数?如果是这样,你如何正确实施?
我们建议对输出和属性使用Collection,ReadOnlyCollection或KeyedCollection,并使用IEnumerable,ICollection,IList作为输入.
例如,
public ClassA
{
private Collection<String> strings;
public Collection<String> Strings { get { return strings; } }
public ClassA(IEnumerable<String> strings)
{
this.strings = strings; // this does not compile
this.strings = strings as Collection<String>; // compiles (and usually runs?)
}
}
Run Code Online (Sandbox Code Playgroud)
你应该避免向下倾斜; 在你的例子我建议你的构造器参数的类型应当匹配(应该是相同)的部件的数据的类型(即,任一 Collection<String>
或 IEnumerable<String>
).
或者有Marc的解决方案,这是不同的:因为Marc的解决方案意味着您的成员数据不仅是一个不同的类型,它也是一个不同的实例(即如果您修改成员数据,那么您正在修改原始集合的副本,而不是编辑原始集合本身;类似地,如果在复制后修改了原始集合,则本地副本/成员数据不包括对原始集合的后续更改).