Is it possible to wrap a C# singleton in an interface?

后端 未结 4 900
挽巷
挽巷 2021-02-20 05:28

I currently have a class in which I only have static members and constants, however I\'d like to replace it with a singleton wrapped in an interface.

But how can I do th

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-20 05:55

    You can't do this with interfaces since they only specify instance methods but you can put this in a base class.

    A singleton base class:

    public abstract class Singleton where ClassType : new()
    {
      static Singleton()
      {
      }
    
      private static readonly ClassType instance = new ClassType();
    
      public static ClassType Instance
      {
        get
        {
          return instance;
        }
      }
    }
    

    A child singleton:

    class Example : Singleton
    {
      public int ExampleProperty { get; set; }
    }
    

    A caller:

    public void LameExampleMethod()
    {
      Example.Instance.ExampleProperty++;
    }
    

提交回复
热议问题