Sometimes, you need to create a data structure when programming. There are data members in this data structure that have methods (or only data, only methods are possible), but these are common things, it does not need to interact or change during running, and the content is correlated. I want them to be a relatively whole block, so it naturally needs to be a structure or class, however, I don't want this block to be converted out of the instance, and I don't want it to be inherited. In this case, you need to declare the constructor as private. In this way, no matter whether it is a structure or a class, it cannot be instantiated, so it can only be accessed directly through the class name, it should be accessed through the class name, the member variables and member functions that need to be accessed by the outside world must be static. As follows:
Class commonfunction ()
{
Private commonfunction (){};
Static datetime startdate = new datetime (2010, 06, 01 );
Static string companeyname = "ZT tec ";
Static void printconfidential ()
{
Console. writeline ("these information are zt tec confidential !!! ");
}
//........
}
If you want to construct a class that can be instantiated, but do not want to be inherited, you can define the sealed class for implementation. The method is very simple. Just add sealed before the class name, if a class inherits from the class, an error is reported during compilation.
If we want to construct a class to be inherited but not instantiated, we can define an abstract class for implementation.
Now. in net/C #, you can also define such a type, called static class, which is the same as the case mentioned in the first case: it cannot be instantiated or inherited, however, it has a rule that all member variables and member methods must be static !!! This result seems to be exactly the same as the class that defines the private constructor, but it seems that the class that defines the private constructor should be more flexible. Because, after all, in a class, you may need to extract some steps into a method for other methods in the class to call. If it is static, it cannot be done.
I haven't thought of anything else to pay attention to for the moment. To be supplemented.