gpt4 book ai didi

c# - Base to Derived 是可能的(装箱),但是 Derived to base 会给出运行时异常,但这等同于 Unboxing

转载 作者:行者123 更新时间:2023-12-05 01:47:55 28 4
gpt4 key购买 nike

Base to Derived 是可能的(装箱)。但是 Derived to base 给出了运行时异常,然而这相当于拆箱。为什么会这样

Base b = new Base();
Child c = new Child();
c = (child)b; // No compilation error but run time error

object a;
int i = (int)a; //No error Unboxing

有没有可能是因为object是top class all value type或者Object类继承的Ref type。 公共(public) int ConvertToINT(对象 obj) { int i = (int)obj; 返回 Convert.ToInt32(obj);

最佳答案

您混淆了值装箱和引用转换。

如果你这样做:

int x = 1;
object a = x;
int i = (int) a;

然后 object a = x; 行通过(有效地)创建包含整数值 1 的包装类来装箱 x 的整数值。

当您通过将其转换回 int 来取消装箱时,运行时代码会检查其基础类型是否正确(int,因为您正在转换为 int ),然后提取底层值并将其分配给目标 int 变量。

如果你这样做:

public class BaseClass
{
}

public class DerivedClass: BaseClass
{
public int Value;
}

...

BaseClass b = new BaseClass();
DerivedClass d = (DerivedClass) b;
int myValue = d.Value; // What would happen? BaseClass doesn't have a Value property!

这里不涉及装箱,因为我们使用的是引用类型。相反,此代码试图将基类视为派生类。

这显然是不可能的,因为如果您随后尝试访问 DerivedClass.Value 会发生什么情况?基类中不存在该属性,因此无法将基类的实例视为派生类。

关于c# - Base to Derived 是可能的(装箱),但是 Derived to base 会给出运行时异常,但这等同于 Unboxing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20116567/

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