Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何对私有类型使用自定义泛型接口实现?_C#_Generics_Interface_Casting - Fatal编程技术网

C# 如何对私有类型使用自定义泛型接口实现?

C# 如何对私有类型使用自定义泛型接口实现?,c#,generics,interface,casting,C#,Generics,Interface,Casting,假设我想指定在我的类中使用的泛型接口的哪个实现。如果类使用它存储另一个公共类型,那么这很简单(如果有点难看): class Foo<T> where T : IList<Bar>, new() { private T _list = new T(); } class Bar{} 显然,这会失败,因为Foo无法在其类型约束中公开Bar,并且无法实例化newfoo() 我可以坚持公开对象: class Foo<T> where T : IList<

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

class Foo<T> where T : IList<Bar>, new()
{
    private T _list = new T();
}
class Bar{}
显然,这会失败,因为
Foo
无法在其类型约束中公开
Bar
,并且无法实例化
newfoo()

我可以坚持公开
对象

class Foo<T> where T : IList<object>, new()
{
    private T _list = new T();
    class Bar{}
}
类Foo,其中T:IList,new()
{
私有T_列表=新T();
类条{}
}
但每次使用界面时,我都会从
对象
转换到
条形图


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

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

如何在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);
    }
}
类Foo,其中TList:IList,new()
{
私有IList_list=new TList();
公共食物(
{
}
公共无效添加(滴度项目)
{
_列表。添加(项目);
}
}
然后制作一个混凝土类来支撑钢筋

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

我认为您最好的选择是:

class Foo
{
    private List<Bar> _list = List<Bar>();
    class Bar{}
}
class-Foo
{
私有列表_List=List();
类条{}
}

如果您有一个带有Bar继承器的私有嵌套类层次结构,那么我能够理解将Foo作为一个泛型类来包装某个私有嵌套类列表的唯一原因。如果是这样的话,您可以公开某种工厂方法,它使用一个必要的参数来告诉Foo客户机需要哪个子类。如果您将列表和列表的类型都保留为私有,那么将该类的公共API设置为通用是没有意义的,依我看。您要求客户端提供一种他们无法访问或控制的类型。

很抱歉没有立即发布我的完整答案,copy/Paste出现了问题。我不想公开
Bar
。我宁愿不去。我只需要在内部使用它,使用传入的泛型类型。
class Foo
{
    private List<Bar> _list = List<Bar>();
    class Bar{}
}