抱歉,如果这是个愚蠢的问题,我是编程新手 所以,我有几门课,比如:

public class BaseClass
{
    int a;
}
public class ChildClass1:BaseClass
{
    string b;
}
public class ChildClass2:BaseClass
{
    string c;
}

我需要一个数组才能上这些课,我怎么才能做到这一点?

try 使用基类创建数组,但无法访问子类数据.

public BaseClass[] array = new BaseClass[20];

推荐答案

以下代码为is valid.

BaseClass[] array = new BaseClass[20];
array[0] = new BaseClass();
array[1] = new ChildClass1();
array[2] = new ChildClass2();
... // etc

并且所有元素都可以访问基类字段(int a).但是要访问子类,需要进行一些模式匹配

for(int i=0; i<array.Length; i++)
{
    BaseClass item = array[i];
    if(item != null )
    {
        Console.Write(item.a);
    }
    if(item is ChildClass1 child1)
    {
        Console.Write(child1.b);
    }
    if(item is ChildClass2 child2)
    {
        Console.Write(child2.c);
    }
    Console.WriteLine();
}

Csharp相关问答推荐

我们应该如何在IHostedService中使用按请求的GbContent实例?

System.文本.Json现在总是需要无参数构造函数吗?

C# Json重新初始化动态类型

List T.AddRange在传递ConcurrentDictionary作为参数时引发ArgumentExcellent

Plotly.NET访问互联网时出现异常

C#将参数传递给具有变化引用的变量

如何从泛型方法返回一个可为空的T,其中T:notnull?

Azure DEVOPS找不到定制的Nuget包

实体框架核心中的ComplexType和OwnsOne有什么不同?

C#-从基类更新子类

在C#中反序列化/序列化具有混合元素顺序的XML时出现问题

泛型参数在.NET 8 AOT中没有匹配的批注

为什么Azure函数(独立工作进程)索引失败?使用Azure App配置的CosmosDbTrigger绑定失败,未解析为值

{ or ; expected error如何解决此问题

当`JToken?`为空时?

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别

用于分钟和秒验证的MudTextfield的正则表达式掩码

如何使ExecuteAsync异步运行

这是T自身的布尔表达式是什么意思?

同时通过多个IEumable<;T&>枚举