c# - 抽象方法和隐藏方法

标签 c# abstract-class method-hiding

我正在尝试更好地理解 C# 中的抽象类。

我知道在抽象类中你必须覆盖抽象方法并且可以覆盖虚拟方法..

我的问题是:

我可以覆盖非虚拟方法吗? (我知道通常我不能 - 但也许抽象类会有所不同?)或者它会像隐藏一样吗?

还有,正如我在这里读到的How to force call a C# derived method (第一个答案) - 在我看来,因为非虚拟方法在编译时静态链接并且无法更改 - 我将无法调用派生类中的方法,永远不会?如果是这样 - 隐藏方法有什么意义?

最佳答案

I'm trying to understand abstract classes in c# better.

OK,那么让我们改正你的错误,因为你在这里对抽象类的一些完全错误的想法。

I know that in abstract classes you MUST override abstract methods and MAY override virtual methods.

绝对不是;那句话的第一部分是完全错误的。 在抽象类中没有任何要求重写抽象方法。

非抽象类称为具体类。真正的规则是:

  • 具体类必须用具体方法覆盖其所有抽象基类的所有抽象方法;它可以自己实现,也可以通过一个或多个基类实现。

这应该是有道理的:在实现每个抽象方法之前,您不能创建具体类的实例;否则,您可能会调用一个没有实现的方法,那会很糟糕。

  • 任何派生类都可以覆盖其任何基类的非密封虚方法。

can I override non virtual methods?

没有。您可以重载非虚拟方法,也可以隐藏现有的非虚拟方法,但不能覆盖它们。

it seems to me that because non virtual methods statically linked at compile time and can't be changed - I would not be able to call the methods in the derived class ,never?

当然不是。您可以通过将接收者转换为派生类来调用派生类的方法。

what is the point of hiding a method?

副本:

Is method hiding ever a good idea

这是一个您没有问过的奖励问题。看看你能不能回答。

Can a method be marked as both abstract and override? If no, why not? If yes, give an example and explain why you would want to.

如果你能正确回答这个问题,那么你可能对抽象方法有很好的理解。解决方案是here .

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

相关文章:

Ruby隐藏与覆盖

c# - 为什么在 MVC5 中 Optional 参数值会自动填充路由数据?

python - 实现 __contains__ 方法时从 collections.abc.Container 类隐式继承

java抽象类构造函数不会按预期工作

Java - 隐藏重写和修饰符 final

c# - 什么情况下使用 "method hiding"有意义?

c# - 如何在 C# 中初始化静态变量

c# - 如何在 .NET Compact Framework 中获取所有已加载程序集(引用)的编程列表

c# - 为什么类型 System.__ComObject 声称(有时)是公开的,而实际上不是?

java - 扩展抽象类和实现接口(interface)的组合