I have the following two use cases:

class BaseCalculator
{
    public int Sum(int x, int y)
    {
        return x + y;
    }   
}

class Calculator : BaseCalculator
{
    public new int Sum ( int x , int y )
    {
        return x + y;
    }
}

This did explicitly hide the Sum method using the new keyword.

class BaseCalculator
{
    public int Sum(int x, int y)
    {
        return x + y;
    }
}

class Calculator : BaseCalculator
{
    public int Sum ( int x , int y )
    {
        return x + y;
    }
}

I didn't understand the difference between the two. Does the second code implicitly hide the Sum method?

有帮助吗?

解决方案

From MSDN documentation:

In C#, derived classes can contain methods with the same name as base class methods. If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.

And why the two code pieces are the same is explained below:

Using the new keyword tells the compiler that your definition hides the definition that is contained in the base class. This is the default behavior.

The only difference is that by using new keyword, you avoid the compiler warning.

More explanation can also be found on MSDN in Knowing When to Use Override and New Keywords (C# Programming Guide).

其他提示

Yes it does. There is no semantic difference. The new keyword merely emphasizes the hiding. It is similar to the behavior of the private modifier. Members are private by default, but you can write private anyway.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top