C#列表<;T>;遗产

本文关键字:遗产 gt lt 列表 | 更新日期: 2023-09-27 18:26:26

假设我有一个名为Field 的类

public class Field
{
    public string name {get;set;}
    public string type {get;set;}
}

对于我的程序,我需要构建一个List,但List中的一些字段是通用的,并且在程序的几个部分中会重复,我想将那些将被复制的字段分离到基类中,这样这些子类就可以从基类继承,而不必复制一些字段概念大致如下:

base classA {
    List<Field> list = new List<Field>();
    list.add(new Field(){name = "fieldNameA", type = "typeA"});
    list.add(new Field(){name = "fieldNameB", type = "typeB"});
    list.add(new Field(){name = "fieldNameC", type = "typeC"});
}
base classB {
    List<Field> list = new List<Field>();
    list.add(new Field(){name = "fieldNameX", type = "typeX"});
    list.add(new Field(){name = "fieldNameY", type = "typeY"});
    list.add(new Field(){name = "fieldNameZ", type = "typeZ"});
}

sub class {
   private void methodA() {
      //Inherits list initialized at 
      //     **base classA** above, 
      //and continues to initialize some other Fields
     list.add(new Field(){name = "fieldNameD", type = "typeD"});
     list.add(new Field(){name = "fieldNameE", type = "typeE"});
      //so at here finally i would have list which consists of fieldNameA to fieldName E
    }

    private void methodB() {
      //Inherits list initialized at 
      //      **base classB** above, 
      //and continues to initialize some other Fields
     list.add(new Field(){name = "fieldNameD", type = "typeD"});
     list.add(new Field(){name = "fieldNameE", type = "typeE"});
      //so at here finally i would have list which consists of fieldNameX, Y,Z,D,E
    }
}

为了实现这一点,我应该怎么做?

C#列表<;T>;遗产

我不确定你的意思是这样的组成:

class BaseClass {
    protected List<Field> list = new List<Field>();
    public BaseClass()
    {           
       list.add(new Field(){name = "fieldNameA", type = "typeA"});
       list.add(new Field(){name = "fieldNameB", type = "typeB"});
       list.add(new Field(){name = "fieldNameC", type = "typeC"});
    }
}
class SubClass : BaseClass {
    public SubClass() : base()  
    {           
       list.add(new Field(){name = "fieldNameD", type = "typeD"});
       list.add(new Field(){name = "fieldNameE", type = "typeE"});
    }
}