调用基本方法和派生方法 [英] calling both base and derived methods
本文介绍了调用基本方法和派生方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
在C#中,不是如果派生方法是覆盖,而是如果它标记为 new
你必须小心使用这个结构虽然,因为它不是真正的你的对象的消费者预期会发生在大多数情况下;
static class Program
{
static void Main()
{
Base baseObject = new Derived();
Derived derivedObject = new Derived();
Console.Write(derivedObject.Test());
Console.Write(baseObject.Test());
Console.Write(((Base)derivedObject).Test());
}
}
class Base
{
public virtual int Test()
{
return 1;
}
}
class Derived:Base
{
public new int Test()
{
return 2;
}
}
in both C# and C++, is it possible to call both base and derived versions of a method with the same signature instead of overriding the base class version?
解决方案
In C#, not if the derived method is an override, but yes if it is marked as new
. You have to be careful when using this construct though, as it isn't really what a consumer of your object would expect to happen in most cases;
static class Program
{
static void Main()
{
Base baseObject = new Derived();
Derived derivedObject = new Derived();
Console.Write(derivedObject.Test());
Console.Write(baseObject.Test());
Console.Write(((Base)derivedObject).Test());
}
}
class Base
{
public virtual int Test()
{
return 1;
}
}
class Derived : Base
{
public new int Test()
{
return 2;
}
}
这篇关于调用基本方法和派生方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文