c# - 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”类型)并访问派生类的变量。是否可以?
解决方案
这不是继承的工作方式。
子级可以从父级继承,但父级不能继承或访问仅在子级上的任何内容。
但是您可以测试它是否是子类型,然后显式转换,或者在检查时进行转换。
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
}
推荐阅读
- autodesk-forge - 使用 Autodesk Forge API 检索“描述”或“自定义属性”字段
- microsoft-graph-api - 如何使用 Microsoft Graph API 限制对用户和组的访问?
- c# - 将字符串拆分为子字符串,节省大空间
- node.js - 如何在履行对话流中从 Twilio 获取电话号码
- android - 麦克风无法在与自定义 android 应用程序的对话流 Web 集成中工作
- python - 如何让我的 IDE 识别动态添加的功能?
- bash - 用 ffmpeg 分割视频会产生奇怪的输出
- python - Python:如何获取 Active Directory 组成员的电子邮件?
- javascript - 两个 Appium 选择器,其中只有一个接受文本
- java - Aptana Studio 3 不会启动。它只看到 java 1.6 而不是 1.8