Edit Object with xml without creating new Instance

后端 未结 2 794
盖世英雄少女心
盖世英雄少女心 2021-01-15 23:47

I have a class which needs to be a Singleton. It must also be able to load and save its field data in an xml file.

The following method will return a new instance,

2条回答
  •  时光说笑
    2021-01-16 00:03

    why dont you have something like

    public Class TheClassHoldingYourObject
    {
        private static XmlSerializer _instance;
        public static Settings Load() 
        { 
            if(_instance != null) return _instance
            using (Stream stream = File.OpenRead(FileName)) 
            { 
                  XmlSerializer serializer = new XmlSerializer(typeof(Settings)); 
                  return (Settings)serializer.Deserialize(stream); 
            } 
        }
     }
    

    Now you will always get the same instance

提交回复
热议问题