C# 即使在派生类中重写了相同的虚拟方法,也可以通过派生类对象访问基类虚拟方法吗?
这将输出为“这是测试派生的”。是否可以从der.testingSealed()获取“This Is testingSealed base”?您可以使用C# 即使在派生类中重写了相同的虚拟方法,也可以通过派生类对象访问基类虚拟方法吗?,c#,C#,这将输出为“这是测试派生的”。是否可以从der.testingSealed()获取“This Is testingSealed base”?您可以使用base关键字从派生类访问base方法: namespace AbstractImplementation { public class baseclass { public virtual void testingSealed() { Console.WriteLine("
base
关键字从派生类访问base方法:
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();
}
}
}
这将输出:
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();
请注意,C#命名约定要求类和方法以大写字母命名。一旦派生类被实例化,就不能调用基类中的虚拟方法。如果必须调用虚拟方法,则设计中存在缺陷 见此帖: 但是,您可以从重写的方法调用虚拟方法:
This is testingSealed base.
This is testing derived.
This is testingSealed base.
只是不要重写派生类中的方法。如果要获取基消息,为什么不实例化基类型?听起来像是个问题。要访问baaeclass方法,必须创建基类的对象。当基类对象在派生类中被重写时,无法访问它。这个问题是在一次采访中问我的。在这个场景中,我给出了两个答案。1) 如果我们想要访问基2)创建基类对象并访问该方法,则不需要重写派生类中的方法。但他说有一些方法可以通过派生类对象访问派生类中重写的基类方法,当我问这个问题的答案时,他让我找出答案。对虚拟非密封方法使用
call
MSIL指令被认为只有在调用的实例是this
时才可验证,这只能从内部对象实现,而不能从外部代码实现。但这里我们不是实例化对象。我们必须通过实例化派生类来调用base。@user1722137-您能更详细地解释您的注释吗?最好在您没有发布任何代码时添加注释这是问题的第一个正确答案,并且不需要任何代码。如果更多的人不发表无关的东西,世界会变得更好。明白。非常感谢。
public override void testingSealed()
{
base.testingSealed();
Console.WriteLine("This is testing derived");
}