[英]How can I keep a class from being inherited in C#?
In java, I could do this with the 'final' keyword. 在Java中,我可以使用“ final”关键字来完成此操作。 I don't see 'final' in C#.
我在C#中看不到“最终”。 Is there a substitute?
有替代品吗?
You're looking for the sealed
keyword. 您正在寻找
sealed
关键字。 It does exactly what the final
keyword in Java does. 它与Java中的
final
关键字完全一样。 Attempts to inherit will result in a compilation error. 尝试继承将导致编译错误。
Also be aware that "I don't think anybody will ever need to inherit from this" is not a good reason to use "sealed". 另请注意,“我认为没有人需要继承”不是使用“密封”的充分理由。 Unless you've got a specific need to ensure that a particular implementation is used, leave the class unsealed.
除非您有特定的需要确保使用特定的实现,否则请不要密封该类。
As Joel already advised, you can use sealed
instead of final
in C#. 正如Joel所建议的那样,您可以在C#中使用
sealed
而不是final
。
http://en.csharp-online.net/CSharp_FAQ:_Does_CSharp_support_final_classes http://en.csharp-online.net/CSharp_FAQ:_Does_CSharp_support_final_classes
The sealed
modifier will do what final
does in Java. sealed
修饰符将完成final
在Java中的作用。
Also, although this probably isn't what you're looking for in this situation, marking a class as static
also keeps it from being inherited (it becomes sealed behind the scenes). 同样,尽管在这种情况下这可能不是您想要的,但是将类标记为
static
也可以防止其被继承(它在后台被密封)。
sealed
关键字可以使用,但是仍然可以使用反射IIRC从该类派生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.