2011-11-07 32 views
2

假设我想指定在我的类中使用通用接口的实现。这是简单的(如果有点丑)如果类是用它来存储另一个公共类型:如何使用私有类型的自定义通用接口实现?

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

然后我们就可以让富的新实例,因为这样:new Foo<List<Bar>>()

但会发生什么Bar是内Foo私有类:

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

显然,这将失败,因为Foo不能暴露在它的类型约束Bar,而且也没有办法来实例化一个new Foo<List<Bar>>()

我会坚持揭露object

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

但后来我从object我每次使用接口时铸造Bar

这里我最好的选择是什么?

回答

1

私有的目的是只允许通过同一类中的代码访问。只是你试图做的是不正确的。根据您的要求更好地将其私人改为其他访问修改器。

+0

我不想暴露'酒吧'。我不想。我只需要在内部使用它,并使用传入的泛型类型。 – dlras2

0

怎么样在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 { } 
} 
+0

对不起一次没有发布我的完整答案,复制/粘贴出错了 – Polity

0

我会说你最好的选择是:

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

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

相关问题