gpt4 book ai didi

c# - C# 中的虚拟和新功能

转载 作者:行者123 更新时间:2023-11-30 13:44:54 25 4
gpt4 key购买 nike

<分区>

我在 C# 中有以下类:

public class BaseClass
{
public virtual void DoSomethingVirtual()
{
Console.WriteLine("Base.DoSomethingVirtual");
}

public new void DoSomethingNonVirtual()
{
Console.WriteLine("Base.DoSomethingNonVirtual");
}
}

public class DerivedClass : BaseClass
{
public override void DoSomethingVirtual()
{
Console.WriteLine("Derived.DoSomethingVirtual");
}

public new void DoSomethingNonVirtual()
{
Console.WriteLine("Derived.DoSomethingNonVirtual");
}
}

class ConsoleInheritanceTrial
{
static void Main(string[] args)
{
Console.WriteLine("Derived via Base Reference.");

BaseClass BaseRef = new DerivedClass();
BaseRef.DoSomethingVirtual();
BaseRef.DoSomethingNonVirtual();

Console.WriteLine();
Console.WriteLine("Derived via Dereived Reference.");

DerivedClass DerivedRef = new DerivedClass();
DerivedRef.DoSomethingVirtual();
DerivedRef.DoSomethingNonVirtual();

Console.Read();
}
}

运行 Main 函数后,我得到了这个:

Derived Via Base Reference
Derived.DoSomethingVirtual
Base.DoSomethingNonVirtual

Derived Via Derived Reference
Derived.DoSomethingVirtual
Derived.DoSomethingNonVirtual

为什么baseRef.DoSoemthingNonVirtual调用了base函数?它与该函数的派生类中的“new”关键字有关吗?我了解“虚拟”和“覆盖”的重要性。我的困惑是由以下声明引起的:BaseClass BaseRef = new DerivedClass();

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