C#Singleton字典类

时间:2017-11-04 10:06:14

标签: c# dictionary

我有以下类将一个大的静态XML文件加载到字典中。我希望它只在引用时加载XML一次。

`codename1.vendor=CodenameOne
codename1.displayName=GuiBuilderTest1
codename1.icon=icon.png
codename1.arg.java.version=8
codename1.languageLevel=5
codename1.secondaryTitle=GuiBuilderTest1
codename1.version=1.0
codename1.mainName=MyApplication
codename1.ios.certificatePassword=
codename1.arg.ios.newStorageLocation=true
codename1.rim.signtoolDb=
codename1.ios.certificate=
codename1.j2me.nativeTheme=nativej2me.res
codename1.android.keystorePassword=
codename1.rim.signtoolCsk=
codename1.android.keystore=
codename1.android.keystoreAlias=
codename1.rim.certificatePassword=
codename1.ios.provision=
codename1.packageName=com.thinksmart.guibuilder2`

我尝试按照本文https://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C

中的主要功能进行操作

但无法完全翻译为词典

2 个答案:

答案 0 :(得分:2)

使用Jon Skeet完全懒惰且线程安全的单例模式:http://csharpindepth.com/Articles/General/Singleton.aspx

public sealed class Singleton
{
    private Singleton()
    { }

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

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        { }

        internal static readonly Singleton instance = new Singleton();
    }
}

或带有Lazy<T>类型的模式

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()
    { }
}

答案 1 :(得分:0)

你应该使用延迟初始化。试试这个:

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        MyClass.MyXML xml = myClass["someKeyValue"];
    }
}


public class MyClass
{
    private class Path
    {
        public string db;
    }
    public class MyXML { }



    private static Path path = new Path();

    private static readonly string _xmlfile = $"{path.db}database.xml";

    private Dictionary<string, MyXML> content = new Dictionary<string, MyXML>();

    public MyXML this[string key]
    {
        get
        {
            MyXML value = content[key];
            if(key == "someKeyValue" && value == null)
            {
                value = getXmlFromFile(_xmlfile);
                content[key] = value;
            }
            return value;
        }
    }

    public MyClass()
    {

    }

    private MyXML getXmlFromFile(string path)
    {
        return XMLHelper.Deserialize<MyXMLs>(path).content;
    }

}