gpt4 book ai didi

C#:通过继承隐藏实现可以吗?

转载 作者:行者123 更新时间:2023-12-02 17:40:58 25 4
gpt4 key购买 nike

鉴于我有以下代码:

interface IBase {
void DoStuff(double x, double y);
}

class Base : IBase {
public void DoStuff(double x, double y) { Console.WriteLine(x + y); }
}

在不实际使用 override 关键字的情况下覆盖/隐藏基类的行为是一个好习惯吗?下面的代码有没有隐藏的陷阱?

class Derived : Base {
public void DoStuff(double x, double y) { Console.WriteLine(x * y); }
}

这里使用new关键字是否更好?就像这样:

class Derived : Base {
public new void DoStuff(double x, double y) { Console.WriteLine(x * y); }
}

最佳答案

Is it a good practice to override/hide the behavior of the base class without actually using the override keyword?

不能“覆盖”基本方法,因为它不是虚拟。您所能做的就是隐藏它。这很少是一个“好的实践”,但没有什么可以阻止它,所以它是否“好”是高度相关的。

Is it any better to use the new keyword here?

使用new不会改变任何功能。关键字的存在是为了让您可以明确告诉编译器“我知道我正在隐藏一个基本成员”。无论您是否使用 new,行为都是相同的。

关于C#:通过继承隐藏实现可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36993627/

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