【问题标题】:How can I use a custom generic interface implementation with private types?如何将自定义泛型接口实现与私有类型一起使用?
【发布时间】:2011-11-07 01:41:44
【问题描述】:

假设我想指定在我的类中使用的通用接口的实现。如果类使用它来存储另一个公共类型,这很简单(如果有点难看):

class Foo<T> where T : IList<Bar>, new()
{
    private T _list = new T();
}
class Bar{}

然后我们可以像这样创建一个新的 foo 实例:new Foo&lt;List&lt;Bar&gt;&gt;()

但是Bar 发生的事情是Foo 中的私有类:

class Foo<T> where T : IList<Bar>, new()
{
    private T _list = new T();
    class Bar{}
}

显然这会失败,因为Foo 无法在其类型约束中公开Bar,并且无法实例化new Foo&lt;List&lt;Bar&gt;&gt;()

我可以坚持公开object

class Foo<T> where T : IList<object>, new()
{
    private T _list = new T();
    class Bar{}
}

但是每次我使用该界面时,我都会从object 转换为Bar

我最好的选择是什么?

【问题讨论】:

    标签: c# generics interface casting


    【解决方案1】:

    私有的目的是只允许同一类中的代码访问。只是你试图做的事情是不正确的。最好根据您的要求将该私有更改为其他访问修饰符。

    【讨论】:

    • 我不想暴露Bar。我宁愿不这样做。我只需要在内部使用它,传入一个泛型类型。
    【解决方案2】:

    如何在 Foo 类中公开第二个类型参数以公开集合的实例类型,例如:

    class Foo<TList, TItem> where TList : IList<TItem>, new()
    {
        private IList<TItem> _list = new TList();
    
        public Foo()
        {
        }
    
    
        public void Add(TItem item)
        {
            _list.Add(item);
        }
    }
    

    然后制作一个具体的类来像这样保持栏

    class BarFoo : Foo<List<BarFoo.Bar>, BarFoo.Bar>
    {
        class Bar { }
    }
    

    【讨论】:

    • 很抱歉没有立即发布我的完整答案,复制/粘贴出现问题
    【解决方案3】:

    我会说你最好的选择是:

    class Foo
    {
        private List<Bar> _list = List<Bar>();
        class Bar{}
    }
    

    我可以理解使 Foo 成为一个通用类来包装一些私有嵌套类列表的唯一原因是,如果你有一个带有 Bar 继承者的私有嵌套类层次结构。而且,如果是这种情况,您可以只公开某种工厂方法,该方法采用必要的参数来告诉 Foo 客户想要哪个子类。如果您要保持列表的类型和列表都是私有的,那么使类的公共 API 通用是没有意义的,IMO。您要求客户提供他们无法访问或控制的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-18
      • 2022-11-02
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多