简体   繁体   English

C#Singleton字典类

[英]C# Singleton dictionary class

I have the following class which loads a large, static XML file into an dictionary. 我有以下类,它将大的静态XML文件加载到字典中。 I want it to only load it the XML once when referenced. 我希望它仅在引用XML时将其加载一次。

public class MyClass
{

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

    public Dictionary<string, MyXML> content;

    public MyClass()
    {

        var d = XMLHelper.Deserialize<MyXMLs>(_xmlfile);

        content = d.content;

    }

}

I tried following the main function from this article https://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C 我尝试遵循本文的主要功能https://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C

But couldnt quite translate is to the Dictionary 但是无法完全翻译成字典

Use Jon Skeet's fully lazy and thread-safe singleton pattern: http://csharpindepth.com/Articles/General/Singleton.aspx 使用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();
    }
}

or his pattern with the Lazy<T> type 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()
    { }
}

You should use lazy initialisation. 您应该使用惰性初始化。 Try this: 尝试这个:

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;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM