这是我所拥有的类(class)的精简版。
public abstract class BaseParent { }
public abstract class ChildCollectionItem<T>
where T : BaseParent
{
// References a third-party object that acts as the parent to both the collection
// items and the collection itself.
public T parent;
// References the collection to which this item belongs. The owning collection
// will share the same parent type. The second type argument indicates what
// type of items the collection will store.
public ChildCollection<T, ChildCollectionItem<T>> owningCollection;
}
public abstract class ChildCollection<T, U> : CollectionBase
where T : BaseParent
where U : ChildCollectionItem<T>
{
// References a third-party object that acts as the parent to both the collection
// items and the collection itself.
public T parent;
// Adds an item of type 'U' to the collection. When added, I want to set the
// owningCollection value of the item to 'this' collection.
public int Add(U item)
{
int indexAdded = this.List.Add(item);
// THIS LINE IS THROWING A COMPILE ERROR - Cannot convert type
// 'ChildCollection<T, U>' to 'ChildCollection<T, ChildCollectionItem<T>>'
item.owningCollection = this;
return indexAdded;
}
我意识到这个问题可能是由于 ChildCollection 类不知道 ChildCollectionItem 中设置的类型约束,因为如果知道的话,这里就不会有问题。类型“U”应始终为 ChildCollectionItem,其中 ChildCollectionItem“T”始终与 ChildCollection“T”相同。
我需要知道的是,是否有一种方法可以强制转换“this”以便它编译,或者修改我的类/约束以便编译器可以在不强制转换的情况下处理它。
最佳答案
问题是方差之一 - U 可能是除 ChildCollectionItem<T>
之外的某种类型- 它可能是派生自 ChildCollectionItem<T>
的类型, 和 Foo<DerivedClass>
与 Foo<BaseClass>
不兼容.
如何向 ChildCollection<T, U>
引入另一个通用基类? ?
using System.Collections;
public abstract class BaseParent { }
public abstract class ChildCollectionItem<T>
where T : BaseParent
{
public T parent;
public ChildCollection<T> owningCollection;
}
public abstract class ChildCollection<T> : CollectionBase
where T : BaseParent
{
}
public abstract class ChildCollection<T, U> : ChildCollection<T>
where T : BaseParent
where U : ChildCollectionItem<T>
{
public T parent;
public int Add(U item)
{
int indexAdded = this.List.Add(item);
item.owningCollection = this;
return indexAdded;
}
}
关于c# - 连接的通用类的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1601504/