namespace AbstractImplementation
{
public class baseclass
{
public virtual void testingSealed()
{
Console.WriteLine("This is testingSealed base");
}
}
public class derived : baseclass
{
public override void testingSealed()
{
Console.WriteLine("This is testing derived");
}
}
class Program
{
static void Main(string[] args)
{
derived der = new derived();
der.testingSealed();
}
}
}
这将输出为"这是测试派生的"。是否有可能获得"这是测试密封基地"来自der.testingSealed()?
答案 0 :(得分:1)
您可以使用base
关键字从派生类访问基本方法:
public class BaseClass
{
public virtual void TestingSealed()
{
Console.WriteLine("This is testingSealed base");
}
}
public class Derived : BaseClass
{
public override void TestingSealed()
{
base.TestingSealed(); // here
Console.WriteLine("This is testing derived");
}
public void TestingSealedBase()
{
base.TestingSealed(); // or even here
}
}
var der = new Derived();
der.TestingSealed();
der.TestingSealedBase();
这将输出:
This is testingSealed base.
This is testing derived.
This is testingSealed base.
P.S。请注意,C#命名约定要求在UpperCamelCase中命名类和方法。
答案 1 :(得分:1)
一旦实例化派生类,就不能调用基类中的虚方法。如果必须调用虚拟方法,则设计中存在缺陷。
看这篇文章: How can I call the 'base implementation' of an overridden virtual method?
但是,您可以从重写的方法中调用虚方法:
public override void testingSealed()
{
base.testingSealed();
Console.WriteLine("This is testing derived");
}
答案 2 :(得分:-1)
只是不要覆盖派生类中的方法。