谁能告诉我下面的sealed不能编译的原因?但是,如果我用final替换sealed,并将其编译为final,它就可以工作。
private sealed int compInt = 100;
public bool check(int someInt)
{
if (someInt > compInt)
{
return true;
}
return false;
}发布于 2012-04-16 16:12:56
这是因为Java语言中的final意味着很多不同的东西,这取决于您在哪里使用它,而C#中的sealed只适用于类和继承的虚拟成员(方法、属性、事件)。
在Java中,final可以应用于:
sealed.virtual,并且在派生类中可以再次使用sealed防止其他派生类发生这种情况。这就是为什么您在Java.sealed成员比在C#中看到的final成员要少得多,这意味着它们只能被初始化一次。对于字段,C#中的等效字段为readonly.发布于 2012-04-16 16:13:51
C#中的Sealed只能应用于引用类型,并且对继承树有影响。
在实践中,标记为sealed的类型被保证是继承树中的最后一个“叶”,或者简而言之,您不能从声明为sealed的类型派生。
public sealed class Child : Base
{
}
public class AnotherAgain : Child //THIS IS NOT ALLOWED
{
}它不能应用于成员。
发布于 2014-05-30 14:54:54
蒂格伦的答案没有错,而乔伊的答案有点不正确。
首先,你可以进入这个页面:What is the equivalent of Java's final in C#?。
sealed关键字可以应用于class、instance method和property,但不能应用于变量或接口的方法。不能继承具有sealed的类。当sealed放在方法上时,它必须由override在公司。每个struct都是sealed,所以struct不能被继承。检查此图像:

https://stackoverflow.com/questions/10170633
复制相似问题