简体   繁体   中英

generic ? abstract class ? what's the best to design my code?

  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 have the similiar funcions Copy/IsEqual/IsSame as TypeA. TypeBCollection, TypeACollection have the similiar IsSame. The exception is TypeBCollection use TypeB.IsSame, TypeCCollection use TypeC.IsSame.

now, I plan to add 2 new classes: LocData and 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]);
    }
    ...
}

and rewrite existing code,

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

now I'm lost in abstract/virtual/generic/..., which is the best way?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM