gpt4 book ai didi

c# - 我可以为重写的方法调用 base 吗

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

除了使用重构之外,是否可以从 B 类的实例调用方法 A.F()。谢谢..


class Program
{
public class A
{
public virtual void F()
{
Console.WriteLine( "A" );
}
}
public class B : A
{
public override void F()
{
Console.WriteLine( "B" );
}
}

static void Main( string[] args )
{
B b = new B();

//Here I need Invoke Method A.F() , but not overrode..

Console.ReadKey();
}
}

最佳答案

可以使用new 关键字来定义相同(命名)方法的另一个定义。根据引用的类型,您可以调用 AB 实现。

public class A
{
public void F()
{
Console.WriteLine( "A" );
}
}
public class B : A
{
public new void F()
{
Console.WriteLine( "B" );
}
}

static void Main( string[] args )
{
B b = new B();

// write "B"
b.F();

// write "A"
A a = b;
a.F();
}

如果您觉得 new 不是正确的解决方案,您应该考虑编写两个具有可分辨名称的方法。


通常,如果方法被正确重写,则不能从类外部调用基实现。这是一个面向对象的概念。您必须有其他方法。有四种方式(我能想到)来指定这种区分方法:

  • 用另一个名字写一个方法。
  • 写一个同名但签名(参数)不同的方法。这称为重载。
  • 写一个同名方法的新定义(使用new关键字),称为隐藏。
  • 将其放在接口(interface)上并明确实现至少一个。 (类似于new,但基于接口(interface))

关于c# - 我可以为重写的方法调用 base 吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3584006/

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