惰性静态类的基类

时间:2015-03-18 17:11:44

标签: c# generics

我想编写一个实现惰性静态模式基本结构的基类。

public class LazyStatic<T>
{
    private static T _static;
    public static T Static
    {
        get
        {
            if (_static == null) _static = Activator.CreateInstance<T>();
            return _static;
        }
    }
}

完成这个基类后,我会像

一样使用它
public class MyOtherClass : LazyStatic<MyOtherClass>
{
  ...
}

基类是否正确实现?

1 个答案:

答案 0 :(得分:1)

您假设T具有无参数构造函数,但您不必restrict you generic class以便编译器知道:

public class LazyStatic<T> where T : new()
{
    private static T _static;
    public static T Static
    {
        get
        {
            if (_static == null) _static = new T();
            return _static;
        }
    }
}
相关问题