gpt4 book ai didi

c# - 在 C# 中将派生类向上转换为基类

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:18 25 4
gpt4 key购买 nike

我很难通过转换来理解这种情况。出于演示目的,我创建了这些类:

public interface IFoo {}
public class Foo : IFoo
{
public string Name { get; set; }
}
public class Bar : Foo
{
public string Surname { get; set; }
}

现在,在我的 Main 方法中,我创建了一个返回 IFoo 的静态方法:

class Program 
{
static void Main()
{
IFoo iFoo = GetIFoo();
Foo foo = (Foo)iFoo;
//the GetType ext method is executed and it returns Bar
if(foo is Foo)
{
Console.WriteLine($"foo is of type: {foo.GetType()}");
}
Console.ReadLine();
}
static IFoo GetIFoo()
{
var bar = new Bar
{
Name = "MyName",
Surname = "MySurname"
}
return bar;
}
}

问题是:即使我在 GetIFoo 方法中创建了一个 Bar,为什么如果我将 IFoo 转换为 Foo,foo 的类型是 Bar 而不是 Foo?

最佳答案

why is it that if I'm casting the iFoo to Foo, foo's type is Bar and not Foo?

这是因为转换改变了静态类型。它对动态类型没有影响。 foostatic 类型是Foo,但它的dynamic 类型是Bar

每个变量都有一个编译器已知的类型(静态类型)和一个运行时已知的类型(动态类型)。在某些情况下,这两种类型是相同的,但它们不必始终相同。

静态类型是变量的声明类型。动态类型是在将对象分配给该变量后通过调用 GetType 获得的类型。

当变量的静态类型与其动态类型不匹配时,您构造了一个示例:iFoo 的静态类型为 IFoo,但其动态类型为 。这非常好,因为 BarIFoo 兼容,因为它实现了接口(interface),也与 Foo 兼容,因为它扩展了类。

关于c# - 在 C# 中将派生类向上转换为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44482921/

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