簡體   English   中英

序列化自定義配置

[英]Serializing custom configuration

我需要一些幫助來實現一種序列化自定義配置的方法。 我從以下示例的內容開始: 多態自定義配置部分

讀取配置按預期工作正常,但我無法保存對某些配置屬性的修改(例如,將屬性 P1 更改為包含另一個字符串)。 雖然調試不同對象的內容看起來很好(部分包含包含三個代理項的集合,這些代理項本身包含一個父類的實例)。 已更改的項目 (P1="") 的 isModified 標志設置為 true(如預期)。

當調用 config.Save() 時出現了一些奇怪的行為,經過三天的調查(甚至是 Microsoft 基類),我無法找出問題所在。 以下是我的一些結論:

我為每個 SerializeX 方法(SerializeSection、SerializeElement 和 SerializeToXmlElement)添加了一個覆蓋,並通過代碼逐步調試。

  • SerializeSection使用參數 parentElement 調用(如預期),這不是我想要序列化的部分,因為 Collection 屬性為空(我希望它具有作為配置文件一部分的三個實例)。 使用this而不是parentElement調用 base.SerializeSection 可以解決問題

  • SerializeToXmlElementSerializeElement之前調用並且確實包含 XmlWriter 的實例(如預期)

  • SerializeElementSerializeToXmlElement之后立即調用並且不再包含 XmlWriter 的實例

  • 當進入集合對象的序列化方法時,我希望集合的三個元素被序列化。 但該集合只包含一個新初始化的項目而不是三個項目,因此具有返回 null 的Parent屬性。

我知道需要有一個自定義的 SerializeElement 方法(可能在 Proxy 類上),然后像反序列化一樣為每個元素調用_Parent.ProxySerializeElement(writer, serializeCollectionKey) 但我無法讓它發揮作用。 SerializeElement 的覆蓋不起作用,因為XmlWriter 實例始終為 null (即使 Proxy 類具有一些 IsModified 方法來檢查 Parent 對象是否已更改)。 此外,一旦我輸入此自定義 SerializeElement 方法,Parent 對象也始終為 null。

以下是我添加到示例中的代碼片段:

父.cs

new public bool IsModified { get { return IsModified(); } }

public virtual bool ProxySerializeElement(XmlWriter writer, bool serializeCollectionKey)
{
    return SerializeElement(writer, serializeCollectionKey);
}

代理.cs

protected override bool IsModified()
{
    bool isModified = base.IsModified();
    return isModified || (Parent == null ? false : Parent.IsModified);
}

protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
{
    bool serialize = base.SerializeElement(writer, serializeCollectionKey);
    return serialize || (_Parent == null ? false : _Parent.ProxySerializeElement(writer, serializeCollectionKey));
}

它讓我發瘋,我無法讓它工作。 也許其他人可以幫助我。

提前謝謝!

你好,史蒂菲

最后這對我有用。 也許它可以幫助遇到同樣問題的其他人。 我將發布完整的代碼以保持簡單。 它可能不是一流的解決方案,但它正在起作用。 如果其他人可以查看它並提出更好的方法,我將不勝感激。

幫助我讓它工作的是這篇文章: https : //www.codeproject.com/Articles/16466/Unraveling-the-Mysteries-of-NET-2-0-Configuration

我的代碼缺少元素集合(請參閱 ThingElement.cs)。

東西.config

<configuration>
  <configSections>
    <section name="ExampleSection" type="ConsoleApplication1.Things.ExampleSection, ConsoleApplication1" />
  </configSections>

  <ExampleSection>
    <things>
      <thing type="one" name="one-1" color="green" />
      <thing type="one" name="one-2" color="red" />
      <thing type="two" name="two-1" />
    </things>
  </ExampleSection>
</configuration>

ExampleSection.cs

    public class ExampleSection : ConfigurationSection
    {
        static ExampleSection() { }

        [ConfigurationProperty("things")]
        [ConfigurationCollection(typeof(ThingElement), AddItemName = "thing",
            CollectionType = ConfigurationElementCollectionType.BasicMap)]
        public ExampleThingElementCollection Things
        {
            get { return (ExampleThingElementCollection)this["things"]; }
            set { this["things"] = value; }
        }
    }

ExampleThingElementCollection.cs

    [ConfigurationCollection(typeof(ThingElement), AddItemName = "thing",
       CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class ExampleThingElementCollection : ConfigurationElementCollection
    {
        #region Constructors
        public ExampleThingElementCollection()
        {
        }
        #endregion

        #region Properties
        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }
        protected override string ElementName
        {
            get { return "thing"; }
        }
        #endregion

        #region Indexers
        public ThingElement this[int index]
        {
            get { return (ThingElement)base.BaseGet(index); }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }
        new public ThingElement this[string name]
        {
            get { return (ThingElement)base.BaseGet(name); }
        }
        #endregion

        #region Overrides
        protected override ConfigurationElement CreateNewElement()
        {
            return new ThingElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as ThingElement).Name;
        }
        #endregion

        #region Methods
        public void Add(ThingElement thing)
        {
            base.BaseAdd(thing);
        }
        public void Remove(string name)
        {
            base.BaseRemove(name);
        }
        public void Remove(ThingElement thing)
        {
            base.BaseRemove(GetElementKey(thing));
        }
        public void Clear()
        {
            base.BaseClear();
        }
        public void RemoveAt(int index)
        {
            base.BaseRemoveAt(index);
        }
        public string GetKey(int index)
        {
            return (string)base.BaseGetKey(index);
        }
        #endregion
    }

ThingElement.cs(此類充當代理元素)

    public class ThingElement : ConfigurationElement
    {
        #region Constructors
        /// <summary>
        /// Predefines the valid properties and prepares
        /// the property collection.
        /// </summary>
        static ThingElement()
        {
            // Predefine properties here
            s_propName = new ConfigurationProperty(
                "name",
                typeof(string),
                null,
                ConfigurationPropertyOptions.IsRequired
            );
        }
        #endregion

        #region Static Fields
        private static ConfigurationProperty s_propName;
        private static Dictionary<string, SpecialThing> elements = new Dictionary<string, SpecialThing>();
        #endregion


        #region Properties
        /// <summary>
        /// Gets the Name setting.
        /// </summary>
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return (string)base[s_propName]; }
        }

        public SpecialThing Thing { get { return elements[Name]; } }

        protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
        {
            return Thing.ProxySerializeElement(writer, serializeCollectionKey);
        }

        protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
        {
            SpecialThing obj = null;
            string name = reader.GetAttribute("name");
            string type = reader.GetAttribute("type");
            switch (type)
            {
                case "one":
                    obj = new One();
                    break;
                case "two":
                    obj = new Two();
                    break;
                default:
                    throw new ArgumentException(string.Format("Invalid type: {0}", type));
            }

            base[s_propName] = name;
            if (!elements.ContainsKey(name))
                elements.Add(name, obj);
            obj.ProxyDeserializeElement(reader, serializeCollectionKey);
        }
        private Hashtable attributes;

        public Hashtable Attributes
        {
            get
            {
                if (attributes == null)
                    attributes = new Hashtable(StringComparer.OrdinalIgnoreCase);
                return attributes;
            }
        }

        protected override bool OnDeserializeUnrecognizedAttribute(String name, String value)
        {
            Attributes.Add(name, value);
            return true;
        }

        protected override void PreSerialize(XmlWriter writer)
        {
            if (attributes != null)
            {
                IDictionaryEnumerator e = attributes.GetEnumerator();
                while (e.MoveNext())
                {
                    string xmlValue = (string)e.Value;
                    string xmlName = (string)e.Key;

                    if ((xmlValue != null) && (writer != null))
                    {
                        writer.WriteAttributeString(xmlName, xmlValue);
                    }
                }
            }
        }

        #endregion
    }

SpecialThing.cs(父類,例如基類,如果您有其他派生類)

    public class SpecialThing : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return (string)this["name"];
            }

            set
            {
                this["name"] = value;
            }
        }

        [ConfigurationProperty("type", IsRequired = true)]
        public string Type
        {
            get
            {
                return (string)this["type"];
            }

            set
            {
                this["type"] = value;
            }
        }

        public virtual bool ProxySerializeElement(XmlWriter writer, bool serializeCollectionKey)
        {
            return SerializeElement(writer, serializeCollectionKey);
        }

        public void ProxyDeserializeElement(XmlReader reader, bool serializeCollectionKey)
        {
            DeserializeElement(reader, serializeCollectionKey);
        }
    }

One.cs(父類,例如基類,如果您有其他派生

    public class One : SpecialThing
    {
        public One() { }

        public One(string name, string type, string color)
        {
            base.Name = name;
            base.Type = type;
            Color = color;
        }

        [ConfigurationProperty("color")]
        public string Color
        {
            get { return (string)this["color"]; }
            set { this["color"] = value; }
        }
    }

二.cs

    public class Two : SpecialThing
    {
        public Two() { }

        public Two(string name, string type)
        {
            base.Name = name;
            base.Type = type;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM