我想创建一个静态类或单例类,它接受在其构造函数中对另一个对象的引用.静态类已经出来了,但我想我可以创建一个在其构造函数中接受参数的单例.到目前为止,我没有任何运气搞清楚或谷歌搜索语法.这可能吗?如果是的话,我该怎么做?
对不起,在最初的帖子中没有任何例子,我匆匆写了.我觉得我的回答已经在回复中了,但这里有一些关于我想做的事情的澄清:
我想创建一个特定类型的单个实例(表示Singleton),但该类型的单个实例需要保存对不同对象的引用.
例如,我可能想要创建一个Singleton"Status"类,它拥有一个StringBuilder对象和一个Draw()方法,可以调用该方法将所述StringBuilder写入屏幕.Draw()方法需要知道我的GraphcisDevice才能绘制.所以我想这样做:
public class Status
{
private static Status _instance;
private StringBuilder _messages;
private GraphicsDevice _gDevice;
private Status(string message, GraphicsDevice device)
{
_messages.Append(message);
_gDevice = device;
}
// The following isn't thread-safe
// This constructor part is what I'm trying to figure out
public static Status Instance // (GraphicsDevice device)
{
get
{
if (_instance == null)
{
_instance = new Status("Test Message!", device);
}
return _instance;
}
}
public void UpdateMessage
...
public void Draw()
{
// …Run Code Online (Sandbox Code Playgroud) 我有一个问题,这是制作Generic Singleton的正确方法吗?
public class Singleton<T> where T : class, new()
{
private static T instance = null;
private Singleton() { }
public static T Instancia
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
检查一些PDF我发现一个通用的Singleton用另一种方式制作,这是另一个正确吗?
public class Singleton<T> where T : class, new()
{
Singleton() { }
class SingletonCreator
{
static SingletonCreator() { }
// Private object instantiated with private constructor
internal static readonly T instance = new T();
}
public static …Run Code Online (Sandbox Code Playgroud)