我的课程结构如下:
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放置单例类的最佳原因是什么?谢谢
像任何其他单身人士一样.
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)