Java 在 C# 中的 final 相当于什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1327544/
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-08-06 15:11:13  来源:igfitidea点击:

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

c#access-modifiersreserved-words

提问by Nosrama

What is the equivalent of Java's finalin C#?

finalC#中Java的等价物是什么?

采纳答案by Noldorin

The finalkeyword has several usages in Java. It corresponds to both the sealedand readonlykeywords in C#, depending on the context in which it is used.

final关键字在 Java 中有多种用法。它对应于 C# 中的sealedreadonly关键字,具体取决于使用它的上下文。

Classes

班级

To prevent subclassing (inheritance from the defined class):

防止子类化(从定义的类继承):

Java

爪哇

public final class MyFinalClass {...}

C#

C#

public sealed class MyFinalClass {...}

Methods

方法

Prevent overriding of a virtualmethod.

防止覆盖virtual方法。

Java

爪哇

public class MyClass
{
    public final void myFinalMethod() {...}
}

C#

C#

public class MyClass : MyBaseClass
{
    public sealed override void MyFinalMethod() {...}
}

As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual, whereas C# marks them as sealed. Hence, you only need to use the sealedkeyword in C# if you want to stop further overriding of a method that has been explicitly marked virtualin the base class.

正如 Joachim Sauer 指出的那样,这两种语言之间的显着区别是 Java 默认将所有非静态方法virtual标记为,而 C# 将它们标记为sealed. 因此,sealed如果您想停止进一步覆盖已virtual在基类中显式标记的方法,则只需在 C# 中使用关键字。

Variables

变量

To only allow a variable to be assigned once:

只允许一个变量被赋值一次:

Java

爪哇

public final double pi = 3.14; // essentially a constant

C#

C#

public readonly double pi = 3.14; // essentially a constant

As a side note, the effect of the readonlykeyword differs from that of the constkeyword in that the readonlyexpression is evaluated at runtimerather than compile-time, hence allowing arbitrary expressions.

作为边注,所述的效果readonly关键词不同于所述的const,所述关键字readonly表达在评价运行时,而不是编译时,因此允许任意表达式。

回答by LukeH

It depends on the context.

这取决于上下文。

回答by x2.

sealed

密封

回答by Krzysztof Krasoń

http://en.csharp-online.net/CSharp_FAQ:_What_are_the_differences_between_CSharp_and_Java_constant_declarations

http://en.csharp-online.net/CSharp_FAQ:_What_are_the_differences_between_CSharp_and_Java_constant_declarations

C# constants are declared using the const keyword for compile time constants or the readonly keyword for runtime constants. The semantics of constants is the same in both the C# and Java languages.

C# 常量使用 const 关键字声明为编译时常量或 readonly 关键字用于运行时常量。常量的语义在 C# 和 Java 语言中是相同的。

回答by Vijayakumarpl

Java class final and method final -> sealed. Java member variable final -> readonly for runtime constant, const for compile time constant.

Java 类 final 和方法 final -> 密封。Java 成员变量 final -> readonly 用于运行时常量,const 用于编译时常量。

No equivalent for Local Variable final and method argument final

局部变量 final 和方法参数 final 没有等价物

回答by Some guy

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

这里的每个人都缺少 Java 对 final 成员变量的明确赋值的保证。

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

对于具有最终成员变量 V 的类 C,通过 C 的每个构造函数的每条可能的执行路径都必须只分配 V 一次 - 未能分配 V 或分配 V 两次或更多次将导致错误。

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

C# 的 readonly 关键字没有这样的保证 - 编译器非常乐意保留 readonly 成员未分配或允许您在构造函数中多次分配它们。

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

所以,final 和 readonly(至少在成员变量方面)绝对不是等价的——final要严格得多。

回答by Vlasec

As mentioned, sealedis an equivalent of finalfor methods and classes.

如前所述,sealed相当于final方法和类。

As for the rest, it is complicated.

至于其余的,就复杂了。

  • For static finalfields, static readonlyis the closest thing possible. It allows you to initialize the static field in a static constructor, which is fairly similar to static initializer in Java. This applies both to constants (primitives and immutable objects) and constant references to mutable objects.

    The constmodifier is fairly similar for constants, but you can't set them in a static constructor.

  • On a field that shouldn't be reassigned once it leaves the constructor, readonlycan be used. It is not equal though - finalrequires exactly one assignment even in constructor or initializer.
  • There is no C# equivalent for a finallocal variable that I know of. If you are wondering why would anyone need it: You can declare a variable prior to an if-else, switch-caseor so. By declaring it final, you enforce that it is assigned at most once.

    Java local variables in general are required to be assigned at least once before they are read. Unless the branch jumps out before value read, a final variable is assigned exactly once. All of this is checked compile-time. This requires well behaved code with less margin for an error.

  • 对于static final字段,static readonly是最接近的可能。它允许您在静态构造函数中初始化静态字段,这与 Java 中的静态初始化程序非常相似。这适用于常量(原语和不可变对象)和对可变对象的常量引用。

    const修正是常数非常相似,但你不能将它们放置在静态构造函数。

  • 在离开构造函数后不应重新分配的字段上,readonly可以使用。但它并不相等 -final即使在构造函数或初始值设定项中也只需要一次赋值。
  • final我所知道的局部变量没有 C# 等效项。如果您想知道为什么有人需要它:您可以在 if-else、switch-case 等之前声明一个变量。通过将其声明为 final,您强制它最多被分配一次。

    Java 局部变量通常需要在读取之前至少分配一次。除非分支在读取值之前跳出,否则最终变量只会被赋值一次。所有这些都在编译时检查。这需要行为良好的代码,错误余量较小。

Summed up, C# has no direct equivalent of final. While Java lacks some nice features of C#, it is refreshing for me as mostly a Java programmer to see where C# fails to deliver an equivalent.

总而言之,C# 没有直接等价于final. 虽然 Java 缺少 C# 的一些不错的特性,但对于我来说,作为一个主要的 Java 程序员,看到 C# 无法提供等价物的地方让我耳目一新。