Use sealing in .NET

zhaozj2021-02-16  51

In this article, I will discuss how to create and use seals. I will also tell you where Microsoft's .NET class library uses sealing.

The seal is used to limit the inheritance characteristics of object-oriented programming. Once a class is defined as a seal, it will not be inherited.

In C #, we use keyword SeaD to define a sealing class, and we use keyword notinheritable to complete this feature in Visual Basic .NET. If a class is trying to get from the seal, the compiler will throw an error.

If you are more careful, you may notice that Structs is sealed, so you cannot generate a derived class from Structs.

In C #, use the following class definition statement to define a seal:

// Sealed Classsealed Class SealedClass {....}

In the following code, I defined a seal SeaDClass and this seal was used in Class1. If you run this code, it will work properly. But once you try to generate a derived class from SealedClass, it will be wrong when compiling.

Using system; class class1 {static void main (string [] args) {teacherdclass readydcls = new sexclass (); int total = sealedcls.add (4, 5); console.writeline ("total =" Total.toString () }}

// Sealed Classsealed Class SealedClass {

Public Int Add (int x, int y) {return x y;}}

Why use seals?

We have just seen how to create and use a seal. The main purpose of using the seal is to make the user unable to obtain inheritance features so that users cannot send their own classes from a sealing class. When there is a static member in your class, you can define it into a seal, which is one of the best use of the seal. For example, the PENS class under the System.Drawing namespace (all standard color pen) and Brushes class (all standard color brushs) are two seals.

The PENS class represents all standard colors of the pen. This class is just a static member. For example, Pens.Blue represents a pen in blue color. Similarly, the Brushes class represents a brush of all standard colors, brushes.blue represents a brush of blue color.

So, when you design your app, you should remember that you can use a seal to prevent other users from inheriting your class.

About the author: Mahesh Chand is C # Corner administrator and founder. Since the .NET beta release, Mahesh has been using .NET programming. He is currently in ADO.NET, GDI , AND WINDOWS AND Web Forms. Everyone can contact him through McB@mindcracker.com.

转载请注明原文地址:https://www.9cbs.com/read-23441.html

New Post(0)