C# Seal 和 Java 的 Final 关键字在功能上有什么区别吗?

发布于 2024-08-17 18:20:13 字数 313 浏览 8 评论 0原文

可能的重复:
C# 中 Java 的final 相当于什么?

在 Java 中,final 不仅仅适用于类。

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

谢谢你,很抱歉问了一个相对菜鸟的问题。

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

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

In Java final applies to more than just a class.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

优雅的叶子 2024-08-24 18:20:13

Java 的 final 关键字相当于 C# 的 sealedreadonlysealed 关键字。

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

在 Java 中,方法默认是虚拟的,因此任何方法都可以声明为 final 以防止其被重写。在 C# 中,方法默认不是虚拟的,因此唯一被重写的方法可以声明为 sealed (以防止它们被进一步重写)

在 Java 中,任何变量或字段都可以声明为 final< /code> 以防止它在初始化后被更改(并且,对于字段,在构造函数之外)。在 C# 中,可以将字段声明为只读,以获得完全相同的效果,但局部变量则不能。请注意,Java 没有与 C# 的 const 关键字等效的关键字。 (C# 中的 const 在编译时求值,值是硬编码的而不是被引用)

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

Java's final keyword is the equivalent of C#'s sealed, readonly, and sealed keywords.

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

In Java, methods are virtual by default, so any method can be declared final to 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)

In Java, any variable or field can be declared final to 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 const keyword. (consts in C# are evaluated at compile-time, and the values are hard-coded instead of being referenced)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文