public sealed class Singleton { static readonly Singleton instance=new Singleton(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Singleton() { } Singleton() { } public static Singleton Instance { get { return instance; } } }
I think that even when deleting a keyword readonlyfrom an instance of an element, a instancesingleton will work equally well.
readonly
instance
Please help me correct my understanding of the concepts here.
, readonly, Singleton. , - , , , readonly , .
EDIT :
, .can not , .
, , . , - . , , . , , singleton , readonly . , , , : ) ) .
readonly , , , . readonly , . .
, - . readonly - . readonly - .
, , :
public sealed class Singleton { private Singleton() { // Initialize here } private static volatile Singleton _singletonInstance; private static readonly Object syncRoot = new Object(); public static Singleton Instance { get { if(_singletonInstance == null) { lock(syncRoot)) { if(_singletonInstance == null) { _singletonInstance = new Singleton(); } } } return _singletonInstance; } } }
readonly , OneAtaTimeleton ( Singleton).
Why? Well, the class contained some configuration, which I wanted so that the user (administrator) could change while the application was running. So, I added a static Reload () method to the class, which has:
instance = new Configuration();
therefore, you must remove readonly.
The private version of the constructor loads the configuration (via a non-static method).
Source: https://habr.com/ru/post/1788422/More articles:how to display image retrieved from mysql on jframe - javaНевозможно создать файл в Plan 9 acme - editorHow to override the From parameter in Grails email plugin - emailHow to configure spring web stream using jsf 2.0? - springКак работает ConvertAll (Guid.Parse)? - c#How to catch OptimisticLockException at servlet level? - javaWhy is the "direct database connection" paradigm not welcomed by the Android platform? - androidПолучение вложенного документа из mongo db с помощью java Driver - javaOrdering Jtable items using a specific column - JAVA - javaOffice 2007 Web Components and Using Microsoft Office 12.0 Spreadsheet in Visual Studio C # for Windows - c #All Articles