问题描述
在使用嵌套的泛型集合实现的设计,我偶然发现显然是由C#造成这些限制的不变的泛型:
While implementing a design using nested generic collections, I stumbled across those limitations apparently caused by C#'s invariant Generics:
Cannot convert from 'Collection<subtype of T> to 'Collection<T>'
这意味着,以下将无法正常工作,显然是由于仿制药的不变性:
That means, the following will not work, apparently due to the invariance of Generics:
class Outer<TInner, TInnerItem> where TInner : Inner<TInnerItem>
{
public void Add(TInner item)
{
item.Outer = this; // ERROR:
// Cannot implicitly convert from Outer<TInner, TInnerItem>
// to Outer<Inner<TInnerItem>, TInnerItem>
}
}
class Inner<TInnerItem> : ICollection<TInnerItem>
{
Outer<Inner<TInnerItem>, TInnerItem> _outer;
public Outer<Inner<TInnerItem>, TInnerItem> Outer
{
set { _outer = value; }
}
}
(在实际的代码中,无论内蒙古<>
和外<>
实施的ICollection<>
。)
我需要的内蒙古<>
对象有其容器收集,以获得一个参考它的一些数据。
I need the Inner<>
objects to have a reference to its container collection in order to access some of its data.
您会如何最好使用如上文所述的通用方法实现这些嵌套的集合,?你会如何设置在内蒙古<的参考容器收集;>
类?
How would you implement these nested collections, preferably using a generic approach as outlined above? How would you set the reference to the container collection in the Inner<>
class?
干杯!
推荐答案
引入一个(可能是抽象)基类它不依赖于TINNER可以帮助你:
Introducing a (possibly abstract) base class which is not dependant on TInner may help you:
abstract class OuterBase<TInnerItem>
{
}
class Outer<TInner, TInnerItem> : OuterBase<TInnerItem> where TInner : Inner<TInnerItem>
{
public void Add(TInner item)
{
item.Outer = this; // Compiles
}
}
class Inner<TInnerItem> : ICollection<TInnerItem>
{
OuterBase<TInnerItem> _outer;
public OuterBase<TInnerItem> Outer
{
set { _outer = value; }
}
}
或等待C#4.0,它引入了CO /禁忌变种的通用接口。
Or wait for C# 4.0, which introduces co/contra-variant generic interfaces.
这篇关于嵌套泛型集合:如何实现从项目到容器的参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!