What's the correct way to have Singleton class in c# [duplicate]

浪子不回头ぞ 提交于 2020-05-24 07:56:29

问题


I am learning Singleton design pattern in C#, and I have written below code in two ways, and I want to know Which one is the right way to create a Singleton class:

public sealed class TranslationHelper
{
    // first way
    private static readonly TranslationHelper translationHelper = new TranslationHelper();
    // second way
    public static readonly TranslationHelper translationHelpers = new TranslationHelper(); // Direct call

    public static TranslationHelper GetTranslationHelper()
    {
        return translationHelper;
    }

    private TranslationHelper()
    {
    }
}

CALL:

TranslationHelper instance = TranslationHelper.GetTranslationHelper();
TranslationHelper ins = TranslationHelper.translationHelpers;

I am beginner so I am not sure if both methods are same. Please guide me.


回答1:


If you are using .Net 4 or higher you can use the Lazy<T> type like this:

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

By using this design pattern with a private constructor you are insuring that the class and it is only created at the time it is used. This is ensured because

  1. It can only be called by itself so it does not get instantiated ahead of time.
  2. The Lazy<T> keyword when used with the private static readonly lambda function now provides a visually clear way of lazily creating an instance of the class from within the function itself.
  3. The public Singleton Instance property provides a way to access that singleton from outside the class.


来源:https://stackoverflow.com/questions/52173966/whats-the-correct-way-to-have-singleton-class-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!