如何从C#中的抽象列表访问派生类的成员变量

时间:2018-11-06 21:55:17

标签: c# list derived-class abstract-data-type

这是基类的代码:

public abstract class baseClass
{
    public string Name { get; set; }
}

然后有两个派生类

public derived1: baseClass 
{
    public int derivedMemberVariable { get; set; }
}

public derived2: baseClass 
{
    public string derivedMemberVariableAlternative { get; set; }
}

然后我创建了一个基类列表,并向其中添加了两个派生类型:

List<baseClass> baseList = new List<baseClass>();
derived1 der1 = new derived1{
    Name = "Derived1 Name",
    derivedMemberVariable = 10
};
derived2 der2 = new derived2{
    Name = "Derived2 Name",
    derivedMemberVariable = "STRING"
};

baseList.Add(der1);
baseList.Add(der2);

foreach (b in baseList){
    b.derivedMemberVariable //this is what fails
}

如何从基类创建的列表中访问此派生成员变量?

我必须按原样使用代码,因为它是用于学校项目的,所以我不能修改类的工作方式,但我想可以修改列表?但是列表需要包含两个派生类。

我将能够完成此任务,还是必须采取其他方法?

好的,所以由于某种原因,我这次尝试投射时,它就起作用了!我觉得很蠢:/

感谢AntiTcb指出来。

我最终要做的是:

foreach (b in baseList){
    if(b.GetType() == der1.GetType()){
        var q = b as derived1;
        q.derivedMemberVariable; // now works
    }
    if(b.GetType() == der2.GetType()){
        var q = b as derived2;
        q.derivedMemberVariableAlternative; // now works
    }
}

1 个答案:

答案 0 :(得分:1)

使用模式匹配:

foreach (b in baseList){ 
{
      if(b is DerivedType d) 
      {
             d.derivedMemberVariable //this is  what fails 
      } 
}