Is there a serializable generic Key/Value pair class in .NET?

前端 未结 10 1380
自闭症患者
自闭症患者 2020-11-29 01:59

I\'m looking for a key/value pair object that I can include in a web service.

I tried using .NET\'s System.Collections.Generic.KeyValuePair<> class, but it doe

相关标签:
10条回答
  • 2020-11-29 02:56

    I don't think there is as Dictionary<> itself isn't XML serializable, when I had need to send a dictionary object via a web service I ended up wrapping the Dictionary<> object myself and adding support for IXMLSerializable.

    /// <summary>
    /// Represents an XML serializable collection of keys and values.
    /// </summary>
    /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
    /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
    [XmlRoot("dictionary")]
    public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
    {
        #region Constants
    
        /// <summary>
        /// The default XML tag name for an item.
        /// </summary>
        private const string DEFAULT_ITEM_TAG = "Item";
    
        /// <summary>
        /// The default XML tag name for a key.
        /// </summary>
        private const string DEFAULT_KEY_TAG = "Key";
    
        /// <summary>
        /// The default XML tag name for a value.
        /// </summary>
        private const string DEFAULT_VALUE_TAG = "Value";
    
        #endregion
    
        #region Protected Properties
    
        /// <summary>
        /// Gets the XML tag name for an item.
        /// </summary>
        protected virtual string ItemTagName
        {
            get
            {
                return DEFAULT_ITEM_TAG;
            }
        }
    
        /// <summary>
        /// Gets the XML tag name for a key.
        /// </summary>
        protected virtual string KeyTagName
        {
            get
            {
                return DEFAULT_KEY_TAG;
            }
        }
    
        /// <summary>
        /// Gets the XML tag name for a value.
        /// </summary>
        protected virtual string ValueTagName
        {
            get
            {
                return DEFAULT_VALUE_TAG;
            }
        }
    
        #endregion
    
        #region Public Methods
    
        /// <summary>
        /// Gets the XML schema for the XML serialization.
        /// </summary>
        /// <returns>An XML schema for the serialized object.</returns>
        public XmlSchema GetSchema()
        {
            return null;
        }
    
        /// <summary>
        /// Deserializes the object from XML.
        /// </summary>
        /// <param name="reader">The XML representation of the object.</param>
        public void ReadXml(XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
    
            bool wasEmpty = reader.IsEmptyElement;
    
            reader.Read();
    
            if (wasEmpty)
            {
                return;
            }
    
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                reader.ReadStartElement(ItemTagName);
    
                reader.ReadStartElement(KeyTagName);
                TKey key = (TKey)keySerializer.Deserialize(reader);
                reader.ReadEndElement();
    
                reader.ReadStartElement(ValueTagName);
                TValue value = (TValue)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();
    
                this.Add(key, value);
    
                reader.ReadEndElement();
                reader.MoveToContent();
            }
    
            reader.ReadEndElement();
        }
    
        /// <summary>
        /// Serializes this instance to XML.
        /// </summary>
        /// <param name="writer">The writer to serialize to.</param>
        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
    
            foreach (TKey key in this.Keys)
            {
                writer.WriteStartElement(ItemTagName);
    
                writer.WriteStartElement(KeyTagName);
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();
    
                writer.WriteStartElement(ValueTagName);
                TValue value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();
    
                writer.WriteEndElement();
            }
        }
    
        #endregion
    }
    
    0 讨论(0)
  • 2020-11-29 02:56

    DataTable is my favorite collection for (solely) wrapping data to be serialized to JSON, since it's easy to expand without the need for an extra struct & acts like a serializable replacement for Tuple<>[]

    Maybe not the cleanest way, but I prefer to include & use it directly in the classes (which shall be serialized), instead of declaring a new struct

    class AnyClassToBeSerialized
    {
        public DataTable KeyValuePairs { get; }
    
        public AnyClassToBeSerialized
        {
            KeyValuePairs = new DataTable();
            KeyValuePairs.Columns.Add("Key", typeof(string));
            KeyValuePairs.Columns.Add("Value", typeof(string));
        }
    
        public void AddEntry(string key, string value)
        {
            DataRow row = KeyValuePairs.NewRow();
            row["Key"] = key; // "Key" & "Value" used only for example
            row["Value"] = value;
            KeyValuePairs.Rows.Add(row);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 02:56

    You can use Tuple<string,object>

    see this for more details on Tuple usage : Working with Tuple in C# 4.0

    0 讨论(0)
  • 2020-11-29 02:57

    In the 4.0 Framework, there is also the addition of the Tuple family of classes that are serializable and equatable. You can use Tuple.Create(a, b) or new Tuple<T1, T2>(a, b).

    0 讨论(0)
提交回复
热议问题