newとoverrideの違い 質問する

newとoverrideの違い 質問する

次の違いは何だろうか?

ケース1: 基本クラス

public void DoIt();

ケース1: 継承クラス

public new void DoIt();

ケース2: 基本クラス

public virtual void DoIt();

ケース2: 継承クラス

public override void DoIt();

私が実行したテストに基づくと、ケース 1 と 2 はどちらも同じ効果があるようです。違いや推奨される方法はありますか?

ベストアンサー1

The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.

public class Base
{
    public virtual void DoIt()
    {
    }
}

public class Derived : Base
{
    public override void DoIt()
    {
    }
}

Base b = new Derived();
b.DoIt();                      // Calls Derived.DoIt

will call Derived.DoIt if that overrides Base.DoIt.

The new modifier instructs the compiler to use your child class implementation instead of the parent class implementation. Any code that is not referencing your class but the parent class will use the parent class implementation.

public class Base
{
    public virtual void DoIt()
    {
    }
}

public class Derived : Base
{
    public new void DoIt()
    {
    }
}

Base b = new Derived();
Derived d = new Derived();

b.DoIt();                      // Calls Base.DoIt
d.DoIt();                      // Calls Derived.DoIt

Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.

Source: Microsoft blog

おすすめ記事