首页 > 解决方案 > C#从基类访问派生类变量

问题描述

鉴于以下情况:

public class A
{
  public A()
  {
  
  }

}

public class B : A
{
  public int b;
  
  public B()
  {
    
  }
}

public A a = new B();
print(a.b); // I'd like to have many classes that inherit from A, and storing
// one of them on a single variable. Then access the variables that belong to the //derived class

我的目标是创建几个从基类继承的类。然后将其中一个类分配给一个变量(其类型必须是“A”类型)并访问派生类的变量。是否可以?

标签: c#

解决方案


这不是继承的工作方式。

子级可以从父级继承,但父级不能继承或访问仅在子级上的任何内容。

但是您可以测试它是否是子类型,然后显式转换,或者在检查时进行转换。

 A one = new B();
 A two = new A();

 //Check if one is of type B
 if (one.GetType() == typeof(B))
 {
        //Now you can explicitly cast it.
        B newVar = (B)one; 
 }

if (two.GetType() == typeof(B))
{
        //False, will not reach this point
}

//Cast and check at same time to new variable called first
if(one is B first)
{
        //Logic here using first
}

if (two is B second)
{
        /False, will not reach this point
}

推荐阅读