gpt4 book ai didi

c# - 在 C# 中将一种类型转换为另一种类型

转载 作者:行者123 更新时间:2023-11-30 16:38:23 25 4
gpt4 key购买 nike

我是 OOP 的初学者,只是有一个关于转换的问题,假设我们有:

interface Animal
{
string speak();
}

class Dog : Animal
{
public string speak()
{
return "wan-wan";
}
}

class Cat : Animal
{
public string speak()
{
return "miao";
}

public void catchMouseS()
{
...
}
}

class Program
{
static void Main(string[] args)
{
Animal generic= new Dog();
Cat cutie = (Cat)generic;
}
}

所以你可以看到我可以将狗打成猫,编译器可以接受,编译器不应该足够聪明以抛出错误,因为它肯定会在运行时遇到错误 ' cutie' 调用 catchMouses 方法,因为 cutie 实际上是一只没有 catchMouses 方法的狗?

最佳答案

您描述的案例称为downcasting并且由于您提到的确切原因被认为是错误的代码。它在编译时允许,并在运行时(或不)崩溃(或行为不端)。

您还可以捕获 InvalidCastException并用它做点什么。

关于c# - 在 C# 中将一种类型转换为另一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55033615/

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