C# 密封与 Java 决赛
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10170633/
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
C# sealed vs Java final
提问by Saurabh Ghorpade
Would anybody please tell me as the reason the following use of sealeddoes not compile? Whereas, if I replace sealedwith finaland compile it as Java, it works.
有人请告诉我以下使用sealed无法编译的原因吗?然而,如果我更换sealed与final和编译如Java,它的工作原理。
private sealed int compInt = 100;
public bool check(int someInt)
{
if (someInt > compInt)
{
return true;
}
return false;
}
采纳答案by Joey
That's because finalin Java means plenty of different things depending on where you use it whereas sealedin C# applies onlyto classes and inherited virtual members (methods, properties, events).
这是因为final在Java中,具体取决于您使用它,而意味着很多不同的东西sealed在C#应用只类和继承的虚拟成员(方法,属性,事件)。
In Java finalcan be applied to:
在Javafinal中可以应用于:
- classes, which means that the class cannot be inherited. This is the equivalent of C#'s
sealed. - methods, which means that the method cannot be overridden in a derived class. This is the default in C#, unless you declare a method as
virtualand in a derived class this can be prevented for further derived classes withsealedagain. That's why you seesealedmembers in C# a lot less thanfinalmembers in Java. - fieldsand variables, which means that they can only be initialized once. For fields the equivalent in C# is
readonly.
- classes,这意味着该类不能被继承。这相当于 C# 的
sealed. - methods,这意味着该方法不能在派生类中被覆盖。这是 C# 中的默认值,除非您
virtual在派生类中声明方法,否则可以sealed再次阻止进一步派生类。这就是为什么您sealed在 C# 中看到的成员比final在 Java 中看到的成员少得多的原因。 - fields和variables,这意味着它们只能被初始化一次。对于字段,C# 中的等效项是
readonly.
回答by Tigran
Sealedin C#can be applied only to a reference types, and has impact on inheritance tree.
SealedinC#只能应用于引用类型,并且对继承树有影响。
In practise the type marked as sealedguranteed to be the last "leaf" in the inheritance tree, or in short, you can not derive from the type declared like a sealed.
在实践中,标记为sealed保证的类型是继承树中的最后一个“叶子”,或者简而言之,您不能从像 a 一样声明的类型派生sealed。
public sealed class Child : Base
{
}
public class AnotherAgain : Child //THIS IS NOT ALLOWED
{
}
It can not be applied to a members.
它不能应用于成员。
回答by Shedom Wei
Tigran's answer is not wrong while Joey's is a little incorrect.
Firstly you can look into this page: What is the equivalent of Java's final in C#?.
the sealedkey word can apply to class,instance methodand propertybut not variables, or interface's methods. Classes with sealedcannot be inherited. When sealedput on method, it must be by overridein company. Every structis sealed, so structcannot be inherited. Check this image: 
Tigran 的回答没有错,而 Joey 的回答有点不正确。
首先,您可以查看此页面:Java 在 C# 中的 final 的等价物是什么?.
该sealed关键字可以申请class,instance method而property但不变量,或接口的方法。带类sealed不能被继承。使用sealed方法时,必须override在公司内。Every structis sealed,所以struct不能被继承。检查此图像:

