这是我所学课程的精简版。

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;
  }
}

09-12 08:56