.net - 你接受接口(interface)作为构造函数参数吗?

标签 .net generics constructor interface robustness

是否Krzysztof's建议适用于构造函数?如果是这样,您如何正确实现它?

We recommend using Collection, ReadOnlyCollection, or KeyedCollection for outputs and properties and interfaces IEnumerable, ICollection, IList for inputs.

例如,

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?)
    }
}

最佳答案

你应该避免向下转型;在你的例子中,我建议你的构造函数参数的类型应该匹配(应该相同)你的成员数据的类型(即 either Collection<String> or IEnumerable<String> ).

或者有 Marc 的解决方案,它是不同的:因为 Marc 的解决方案意味着您的成员数据不仅是不同的类型,而且还是不同的实例(即,如果您修改成员数据,那么您正在修改的副本原始集合,而不是编辑原始集合本身;类似地,如果原始集合在您制作副本后被修改,则您的本地副本/成员数据不包括对原始集合的后续更改。

关于.net - 你接受接口(interface)作为构造函数参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/428452/

相关文章:

java - 如何返回通用 ArrayList<T>

java - 对象是否应该知道它需要哪个 'arguments'

c++ - 默认构造函数 C++ 错误

c#:在 my.settings 中存储大量数据

c# - 为什么 Application.LocalUserAppDataPath 抛出 InvalidDeploymentException "Application identity is not set."

java - 泛化类的方法调用

java - 私有(private)不可访问字段是否需要是最终的?

c# - 限制 Windows 工作流的线程

C# 根据日期(月)和组拆分查询结果

.net - 如何将 Cookie 集合转换为通用列表?容易地