简体   繁体   English

C# 访问从 Base class 派生的 class 变量

[英]C# Access derived class variables from Base class

Given the following:鉴于以下情况:

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

My goal here is to create several classes that inherit from a base class. Then assign one of the classes to a variable (whose type must be of type "A") and access the variables of the derived class. Is it possible?我这里的目标是创建几个继承自基类 class 的类。然后将其中一个类分配给一个变量(其类型必须是“A”类型)并访问派生的 class 的变量。这可能吗?

That is not how inheritance works.这不是 inheritance 的工作原理。

A child can inherit from a parent, but a parent does not inherit from nor have access to anything that is only on the child level.子级可以继承父级,但父级不能继承也不能访问仅在子级上的任何内容。

But you can test to see if it is the subtype, and then explicitly cast, or do the cast while checking.但是你可以测试看是不是子类型,然后显式强制转换,或者边检查边强制转换。

 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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