public class SingletonProvider<T> where T : new()
{
SingletonProvider() { }
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}
{
SingletonProvider() { }
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}
Test:
public class TestClass
{
private string _createdTimestamp;
public TestClass ()
{
_createdTimestamp = DateTime.Now.ToString();
}
public void Write()
{
Debug.WriteLine(_createdTimestamp);
}
}
==> : SingletonProvider<TestClass>.Instance.Write();
//另一个实现singleton的方法,不用约束的。
public static class Singleton<T>
{
private static T instance;
public static T NewInstance()
{
if (instance == null)
{
instance = (T) Activator.CreateInstance(typeof(T), true);
}
return instance;
}
}
浙公网安备 33010602011771号