i have this ObservableCollection<MyData> list
that i want to insert inside my Singleton:
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
public static ObservableCollection<MyData> list {get; set;}
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
list = new ObservableCollection<MyData>();
}
}
}
return instance;
}
}
}
Is this the This is the right way to define it ?
答案 0 :(得分:1)
I don't think it is. If the ObservableCollection
should be a member of the Singleton
class, instantiate it in the Singleton's
private constructor. If it shouldn't, I don't see why you doing it this way. What happens when you call Singleton.list
BEFORE Singleton.Instance
? NullReferenceException
. And since its setter is public, it can be set from outside as well which is probably not what you want.
I would modify your code like this:
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
public ObservableCollection<MyData> list {get; private set;}
private Singleton() {
list = new ObservableCollection<MyData>();
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}