gpt4 book ai didi

c# - 隐式和显式方法隐藏

转载 作者:行者123 更新时间:2023-11-30 14:58:07 25 4
gpt4 key购买 nike

我有以下两个用例:

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;
}
}

这确实使用 new 关键字显式隐藏了 Sum 方法。

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;
}
}

我不明白两者之间的区别。第二个代码是否隐式隐藏了 Sum 方法?

最佳答案

来自 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.

下面解释为什么两个代码段相同:

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.

唯一的区别是,通过使用 new 关键字,您可以避免编译器警告。

更多解释也可以在 MSDN 中找到 Knowing When to Use Override and New Keywords (C# Programming Guide) .

关于c# - 隐式和显式方法隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19741131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com