【发布时间】:2011-11-07 01:41:44
【问题描述】:
假设我想指定在我的类中使用的通用接口的实现。如果类使用它来存储另一个公共类型,这很简单(如果有点难看):
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。
我最好的选择是什么?
【问题讨论】:
标签: c# generics interface casting