开发者

What is the real significance of new modifier in C# [duplicate]

This question already has answers here: Closed 11 years ago.

From the code below I wanted to know What is the difference between MyMethod2() and MyMethod3(). Why has .net provided does not give compile error for not mentioning the new keyword or in other words why has .net provided new keyword, if both implemnetation are same.

public class MyBase
{
    public virtual void MyMethod2()
    {
         //do something
    }
    public virtual void MyMethod3()
    {
        //do something
    }
}

public class MyDerived :MyBase
{
    public void MyMethod2()
    {
        base.MyMethod2();
    }
    public new void MyMethod3()
    {
        base.MyMethod3();
    } 
}


   static void Main开发者_如何学运维(string[] args)
    {

        MyBase myClass = new MyDerived();
        myClass.MyMethod2(); //calls base class
        myClass.MyMethod3(); //calls base class
    }


It won't give you a compile error, but it will give you a warning, and act as though you'd used the new keyword.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜