C#泛型继承和协方差 [英] C# generic inheritance and covariance
问题描述
我建立一个集图书馆,我想知道所有的泛型集合接口需要一流的类型和所有实施这些是任何类型的集合。因此,对值类型集合它将有两个方法,一个是值类型和一个拳击它。这是可能的。
I'm building a collection library and I'd like to have all the generic collection interfaces require class types and all the collections implementing them to be any type. So on value types the collection would have two methods, one for the value type and one for boxing it. Is this possible?
是这样的:
interface ICollection<ItemType> where ItemType : class
{
void DoSomething(ItemType item);
}
class Collection<ItemType> : ICollection<ItemType>
{
void DoSomething(Object item);
void DoSomething(ItemType item);
}
除了上述这将是要解决它的最好方法?这些接口是不通用的。
Barring that what would be the best way to get around it? The interfaces being non-generic?
推荐答案
行:
ICollection<Object> s = new Collection<String>();
(评论)将与制定
方差;然而, DoSomething的(的ItemType)
要求在
差异;这样类型可以是既不在
也不退出
:方差的在这里并不适用的
(comments) would work with out
variance; however, DoSomething(ItemType)
would require in
variance; so that type can be neither in
nor out
: variance does not apply here.
这通常处理的方法是有一个通用的和的非通用API。感兴趣的特定类型的人可以使用通用的API; 。人们只是在对象有兴趣的可以使用非通用API
The way that is usually handled is by having a generic and non-generic API. People interested in the specific types can use the generic API; people just interested in "an object" can use the non-generic API.
有关说明:
interface ICollection
{
void DoSomething(object item);
}
interface ICollection<ItemType> : ICollection
{
void DoSomething(ItemType item);
}
class Collection<ItemType> : ICollection<ItemType>
{
void ICollection.DoSomething(Object item)
{
DoSomething((ItemType)item);
}
public void DoSomething(ItemType item)
{
//...
}
}
随后的这个的作品:
ICollection s = new Collection<String>();
object o = "abcd";
s.DoSomething(o);
这篇关于C#泛型继承和协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!