1

This page does a good job of describing how to create c# singletons, but it doesn't seem to explain how you actually use them.

http://msdn.microsoft.com/en-us/library/ff650316.aspx

So if I were to create this singleton below, how do I kick things off (I don't think I can instantiate it directly) and if I don't have an instance object how to I access it - e.g. how do I read and write to property prop1

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();

   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }

   public int prop1 {get; set;}
}
4

4 回答 4

3

要使用单例类,您只需将其称为公共静态实例属性。例如,假设您有一个记录器,并且您不希望其他开发人员总是实例化它:

public class Logger
{
    private static Logger logger = new Logger();

    private Logger() { }

    public static Logger Instance
    {
        get
        {
            return logger;
        }
    }

    public void Log(text)
    {
        // Logging text
    }

    public int Mode { get; set; }
}

您应该以这种方式记录:

Logger.Instance.Log("some text here");

在您的情况下,要读取/写入Mode属性,您应该编写:

Logger.Instance.Mode = 1;
int mode = Logger.Instance.Mode;
于 2013-11-14T17:09:40.217 回答
0

你只创建一次实例,所以你会有这样的东西

public sealed class Singleton
{
   private static readonly Singleton instance;
   private bool initialised = false; 

   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
        if(initialised)
          return instance; 
        else {
               initialsed = true;
               instance = new Singleton();
               return instance; 
             }
      }
   }

   public int prop1 {get; set;}
}
于 2013-11-14T17:26:29.447 回答
0
Singleton.Instance.prop1 = 12;
于 2013-11-14T17:22:54.763 回答
0

您可以通过使用访问实例

Singleton.Instance
于 2013-11-14T17:08:32.330 回答