什么是Java的决赛在C#中的相同呢? [英] What is the equivalent of Java's final in C#?
问题描述
什么是Java的最后
在C#?
What is the equivalent of Java's final
in C#?
推荐答案
最后
关键字在Java中几种用法。它对应于密封的两个
并 只读
在C#中的关键字,这取决于的上下文中使用它。
The final
keyword has several usages in Java. It corresponds to both the sealed
and readonly
keywords in C#, depending on the context in which it is used.
要prevent子类(继承自定义的类):
To prevent subclassing (inheritance from the defined class):
的Java
public final class MyFinalClass {...}
C#
public sealed class MyFinalClass {...}
方法
在虚拟
方法prevent压倒一切的。
Methods
Prevent overriding of a virtual
method.
的Java
public class MyClass
{
public final void myFinalMethod() {...}
}
C#
public class MyClass : MyBaseClass
{
public sealed override void MyFinalMethod() {...}
}
由于约阿希姆绍尔指出,这两种语言之间有显着的区别就在这里是Java在默认情况下标记所有的非静态方法作为虚拟
,而C#将其标记为密封
。因此,你只需要,如果你想停止已明确标记方法的另一个压倒一切的使用密封
关键字在C#虚拟
中的基类。
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 sealed
keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual
in the base class.
要只允许一个变量来分配一次:
To only allow a variable to be assigned once:
的Java
public final double pi = 3.14; // essentially a constant
C#
public readonly double pi = 3.14; // essentially a constant
作为一个侧面说明,只读
关键字不同于在的 常量
在除权pression关键字在评估的运行的而不是编译时间的,因此允许任意的前pressions。
As a side note, the effect of the readonly
keyword differs from that of the const
keyword in that the expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.
这篇关于什么是Java的决赛在C#中的相同呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!