c# - 连接的通用类的转换问题

标签 c# .net generics casting

这是我所拥有的类(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/

相关文章:

c# - 如何在代码隐藏中设置 EntityDataSource 的 Where 子句

c# - 向 XML 节点添加属性

c# - 用于良好编程实践的 Visual Studio 工具

.net - EqualityComparer<Uri>.Default.Equals() 返回错误结果还是什么?

c# - AForge.Net 中的 Blob 过滤

typescript :函数返回类型取决于输入函数返回类型

c# - 我们是否必须在应用程序级别处理蓝牙 LE 通信中的 MTU?

c# - 如何使用扩展方法覆盖 Object.ToString() 方法?

c# - 通用扩展方法解析失败

java - 返回有界通配符