【问题标题】:generic collection not working通用集合不起作用
【发布时间】:2023-04-11 12:52:02
【问题描述】:

我将从代码开始

class LocData 
{
    public virtual TypeA Copy () { ... }
    ...
}

class LocDataCollection<T> : List<T> where T: LocData
{
    public LocDataCollection<T> Copy() 
    {
        LocDataCollection<T> locDatas = new LocDataCollection<T>();
        foreach (T locData in this)
        {
            T locData2 = locData.Copy() as T;
            locDatas.Add(locData2);
        }
        return locDatas;
    }
  ...
}

class TypeA : LocData
{
  public new TypeA Copy () { ... }
  ...
}

class TypeACollection : LocDataCollection<TypeA>
{
}

测试代码:

TypeACollection typeAs = new TypeACollection();
...
TypeACollection typeAs2 = typeAs.Copy();

编译消息:

“无法将类型 'LocDataCollection' 隐式转换为 'TypeACollection'。存在显式转换(您是否缺少强制转换?)”

我要改成

TypeACollection typeAs2 = typeAs.Copy() as TypeACollection;

编译通过但在运行时出错。即使 typeAs 不为 null,typeAs2 也会返回 null。

【问题讨论】:

  • 您在 TypeACollection 中是否有值得创建新类而不是仅使用 LocDataCollection 的特定行为?
  • 是的,TypeACollection 中还有其他功能。

标签: .net generics collections


【解决方案1】:

typeAs.Copy() 返回一个LocDataCollection&lt;TypeA&gt;。但是您不能将其中一个分配给TypeACollection,因为TypeACollectionLocDataCollection&lt;TypeA&gt; 更派生。

您或许可以通过让您的复制方法接收LocDataCollection&lt;T&gt; 来解决问题:

class LocDataCollection<T> : List<T> where T: LocData
{
    public void CopyTo(LocDataCollection<T> dest) 
    {
        ....
    }
}

然后在呼叫现场:

TypeACollection typeAs = new TypeACollection();
TypeACollection typeAs2 = new TypeACollection();
typeAs.CopyTo(typeAs2);

当然,这不会复制任何 TypeACollection 特定内容,除非您添加了覆盖该效果的内容。

但我对您的问题的了解还不够,无法确信这是一个合适的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多