c#sealed 和 Java 的 final 关键字在功能上有区别吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2069010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:14:23  来源:igfitidea点击:

Is there any functional difference between c# sealed and Java's final keyword?

c#javafinalsealed

提问by Hamish Grubijan

Possible Duplicate:
What is the equivalent of Java's final in C#?

可能的重复:
什么是 C# 中 Java 的 final 的等价物?

In Java final applies to more than just a class.

在 Java 中 final 不仅仅适用于一个类。

So, I wonder: is there any functional difference between the two keywords?

所以,我想知道:这两个关键字之间有什么功能上的区别吗?

Thank you, and sorry for a relatively noob question.

谢谢,很抱歉提出一个相对菜鸟的问题。

A quick Google search did not satisfy my needs.

快速的谷歌搜索不能满足我的需求。

回答by SLaks

Java's finalkeyword is the equivalent of C#'s sealed, readonly, and sealedkeywords.

Java的final关键字是等效的C#中sealedreadonlysealed关键字。

Two of those three are somewhat different in Java and C#:

这三个中的两个在 Java 和 C# 中有些不同:

In Java, methods are virtual by default, so any method can be declared finalto prevent it from being overriden. In C#, methods are not virtual by default, so the only overridden methods can be declared sealed(To prevent them from being further overridden)

在 Java 中,方法默认是虚拟的,因此可以声明任何方法final以防止它被覆盖。在 C# 中,默认情况下方法不是虚拟的,因此可以声明唯一覆盖的方法sealed(以防止它们被进一步覆盖)

In Java, any variable or field can be declared finalto prevent it from being changed after initialization (And, for fields, outside the constructor). In C#, fields can be declared readonly, for the exact same effect, but local variables cannot. Note that Java has no equivalent of C#'s constkeyword. (consts in C# are evaluated at compile-time, and the values are hard-coded instead of being referenced)

在 Java 中,可以声明任何变量或字段final以防止它在初始化后被更改(并且,对于字段,在构造函数之外)。在 C# 中,可以声明字段readonly,以获得完全相同的效果,但不能声明局部变量。请注意,Java 没有等效于 C# 的const关键字。(constC# 中的 s 在编译时被评估,并且这些值是硬编码的而不是被引用的)

For classes, C#'s sealedclasses and Java's finalclasses are exactly the same (AFAIK).

对于类,C# 的sealed类和 Java 的final类完全相同(AFAIK)。

回答by Rubens Farias