如何使用私有类型的自定义通用接口实现?

时间:2011-11-07 01:41:44

标签: c# generics interface casting

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

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

然后我们可以创建一个新的foo实例: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

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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 { }
}

答案 2 :(得分:0)

我想说你最好的选择是:

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

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

相关问题