Today, I accidentally sawCodeMaybe I have never seen it. I think it's new. I just wrote the following code. Maybe I 've seen it, Maybe I forgot ...... Haha, let's make a souvenir on your own ......
I found that the singleton mode is good ......
Using System; Namespace Ca_staticconstructor { Class Staticclass { Public Static Staticclass instance { Get ; Set ;} Public String Name { Get ;Set ;} Static Staticclass (){ If(Instance =Null) { Instance = New Staticclass (); } }} Class Program { Static Void Main ( String [] ARGs) {staticclass SC1 = staticclass. instance; sc1.name =" SC1 instance "; Console. writeline (sc1.name); staticclass SC2 = staticclass. instance; // Without Set Name property to instance Console. writeline (sc2.name );}}}
// Result:// SC1 instance// SC1 instance
The preceding code can be simplified as follows:
Using System; Namespace Ca_staticconstructor { Class Staticclass { Public Static Staticclass instance { Get ;Set ;} Public String Name { Get ; Set ;} Static Staticclass () {instance = New Staticclass ();}} Class Program { Static Void Main ( String [] ARGs) {staticclass SC1 = staticclass. instance; sc1.name ="SC1 instance "; Console. writeline (sc1.name); staticclass SC2 = staticclass. instance; // Without Set Name property to instance Console. writeline (sc2.name );}}} // Result: // SC1 instance // SC1 instance
Note thatStaticThe code in staticclass () always needs to judge the construction of the first code in the traditional Singleton, but because the static constructor will invoke during the first call, therefore, in subsequent calls, the instance will be guaranteed, even if it is added, it will not be too much, you can avoid the following form of code destruction:
Static VoidMain (String[] ARGs) {staticclass SC1 = staticclass. instance; sc1.name ="SC1 instance"; Console. writeline (sc1.name );Staticclass. instance =Null;Staticclass SC2 = staticclass. instance;// Without Set Name property to instanceConsole. writeline (sc2.name );}
Of course, we 'd better not and should not have the set method as usual, so that we can ensure that our instance is always the first called instance ......
Using System; Namespace Ca_staticconstructor { Class Staticclass {Private Static Readonly Staticclass instance; Public Static Staticclass instance { Get { Return Instance ;}} Public String Name { Get ; Set ;} Static Staticclass () {instance =New Staticclass ();}} Class Program { Static Void Main ( String [] ARGs) {staticclass SC1 = staticclass. instance; sc1.name =" SC1 instance "; Console. writeline (sc1.name ); // Staticclass. instance = NULL; Staticclass SC2 = staticclass. instance; // Without Set Name property to instance Console. writeline (sc2.name );}}} // Result: // SC1 instance // SC1 instance