gpt4 book ai didi

C# OOPS 说明

转载 作者:行者123 更新时间:2023-12-03 19:08:52 30 4
gpt4 key购买 nike

请问为什么行 "b[0]= new Child2();"在运行时而不是在编译时失败。请不要检查语法,我只是在这里做了

class Base
{}

class Child1 : Base
{}

class Child2 : Base
{}

class Test
{
void Main()
{
Base [] b= new Child1[10];
b[0]= new Child2(); <-- Fails at runtime but not at compile time WHY?
}
}

最佳答案

new Child1[10];

您刚刚声明了一个类型为 Child1 的新数组。

b[0]= new Child2();

现在您正试图将一个兄弟 类放入其中。对象数组可以存储该对象及其子类,但不能存储它的兄弟对象。

关于C# OOPS 说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16981958/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com