通用?抽象类?什么是最好的设计我的代码?

时间:2012-04-19 15:44:23

标签: .net generics collections virtual abstract

  class TypeA 
  {
      public TypeA Copy () { ... }
      public bool IsEqual(TypeA mytypeA) { ... }
      public bool IsSame(TypeA mytypeA) { ... }
      ...
  }

  class TypeACollection : List<TypeA>
  {
      public bool IsSame (TypeACollection typeAs)
      {
          if (Count != typeAs.Count) 
              return false;
          return this[0].IsSame(typeAs[0]);
      }
      ...
  }

TypeB,TypeC具有类似的功能Copy / IsEqual / IsSame作为TypeA。   TypeBCollection,TypeACollection具有类似的IsSame。例外是TypeBCollection使用TypeB.IsSame,TypeCCollection使用TypeC.IsSame。

现在,我计划添加2个新类:LocData和LocDataCollection

class LocData 
{
    public virtual TypeA Copy () { ... }
    public virtual bool IsEqual(TypeA mytypeA) { ... }
    public virtual bool IsSame(TypeA mytypeA) { ... }
    ...
}

class LocDataCollection<T> : List<LocData> where T: LocData
{
    public bool IsSame (LocDataCollection<T> typeAs)
    {
        if (Count != typeAs.Count) 
        return false;
        return this[0].IsSame(typeAs[0]);
    }
    ...
}

并重写现有代码,

class TypeA : LocData
{
    public new TypeA Copy () { ... }
    public new bool IsEqual(TypeA mytypeA) { ... }
    public new bool IsSame(TypeA mytypeA) { ... }
    ...
}

class TypeACollection : ???
{
    ??? 
    // so I can remove IsSame here, 
    // when I call IsSame, it will use one from LocDataCollection and still call 
    // TypeA.IsSame
    ...
}

现在我迷失在抽象/虚拟/通用/ ......中,这是最好的方法吗?

1 个答案:

答案 0 :(得分:1)

您应该将new替换为overrides,然后创建LocDataCollection<T> : Collection<T> where T : LocData