如何让一个类在C#中继承?

时间:2022-09-07 07:49:44

In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?

在java中,我可以使用'final'关键字来完成此操作。我没有在C#中看到'final'。有替代品吗?

5 个解决方案

#1


35  

You're looking for the sealed keyword. It does exactly what the final keyword in Java does. Attempts to inherit will result in a compilation error.

您正在寻找密封关键字。它完全符合Java中的final关键字。尝试继承将导致编译错误。

#2


6  

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.

还要注意“我认为任何人都不需要继承这个”并不是使用“密封”的好理由。除非您确实需要确保使用特定实现,否则请将该类保持为未密封状态。

#3


2  

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

#4


1  

The sealed modifier will do what final does in Java.

密封修饰符将完成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).

此外,虽然这可能不是您在这种情况下所寻找的,但将类标记为静态也会使其不被继承(它在幕后变得密封)。

#5


0  

The sealed keyword would work, but still you can derive from the class using reflection IIRC.

sealed密封关键字可以使用,但您仍然可以使用反射IIRC从类派生。

#1


35  

You're looking for the sealed keyword. It does exactly what the final keyword in Java does. Attempts to inherit will result in a compilation error.

您正在寻找密封关键字。它完全符合Java中的final关键字。尝试继承将导致编译错误。

#2


6  

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.

还要注意“我认为任何人都不需要继承这个”并不是使用“密封”的好理由。除非您确实需要确保使用特定实现,否则请将该类保持为未密封状态。

#3


2  

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

#4


1  

The sealed modifier will do what final does in Java.

密封修饰符将完成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).

此外,虽然这可能不是您在这种情况下所寻找的,但将类标记为静态也会使其不被继承(它在幕后变得密封)。

#5


0  

The sealed keyword would work, but still you can derive from the class using reflection IIRC.

sealed密封关键字可以使用,但您仍然可以使用反射IIRC从类派生。