Singleton继承List <T>

pis*_*hio 0 c# singleton list

我的课程结构如下:

public class MyList: List<MyClass>
{
    internal static bool isConfigured;

    // singleton
    public MyList()
    {
        if (!MyList.isConfigured)
        {
            lock ("isConfigured")
            {
                if (!MyList.isConfigured)
                {
                    // add some elements to MyList parsing them from an XML
                    [..]

                    MyList.isConfigured = true;
                }
            }
        }
    }

    public static MyClass MyStaticMethod(int argument)
    {
        foreach (MyClass c in new MyList())
        {
            // do something
        }
        return // an instance of MyClass
    }

}
Run Code Online (Sandbox Code Playgroud)

当我从单例外部调用MyList.MyStaticMethod()时,我得到以下异常:

[..]
MyClass mc = MyList.MyStaticMethod(1));
[..]

An object reference is required for the non-static field, method, or property 'MyList.get'
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?基于List放置单例类的最佳原因是什么?谢谢

Dan*_*ite 5

像任何其他单身人士一样.

public class MyList: List<MyClass> {
  private readonly static MyList instance = new MyList();

  private MyList() { }

  public static MyList Instance 
  { 
    get 
    {
       return instance;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 作为一个单身人士,这是不可靠的,顺便说一句.OP的双重检查方法,或简单的静态场初始化器等,将更安全. (2认同)