Created
October 27, 2011 18:39
-
-
Save butaji/1320422 to your computer and use it in GitHub Desktop.
Sinlgeton<WTF>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Singleton<T> where T : class | |
{ | |
static volatile T _instance; | |
static object _lock = new object(); | |
static Singleton() | |
{ | |
} | |
public static T Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
lock (_lock) | |
{ | |
if (_instance == null) | |
{ | |
ConstructorInfo constructor = null; | |
// Binding flags exclude public constructors. | |
constructor = typeof(T).GetConstructor(BindingFlags.Instance | | |
BindingFlags.NonPublic, null, new Type[0], null); | |
if (constructor == null || constructor.IsAssembly) | |
// Also exclude internal constructors. | |
throw new InvalidOperationException(string.Format("A private or " + | |
"protected constructor is missing for '{0}'.", typeof(T).Name)); | |
_instance = (T)constructor.Invoke(null); | |
} | |
} | |
return _instance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment