除了使用重构之外,是否可以从 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
关键字来定义相同(命名)方法的另一个定义。根据引用的类型,您可以调用 A
的 B
实现。
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/