当前位置:  开发笔记 > 编程语言 > 正文

.NET中是否有可序列化的通用键/值对类?

如何解决《.NET中是否有可序列化的通用键/值对类?》经验,为你挑选了4个好方法。

我正在寻找一个可以包含在Web服务中的键/值对对象.

我尝试使用.NET的System.Collections.Generic.KeyValuePair<>类,但它没有在Web服务中正确序列化.在Web服务中,Key和Value属性未被序列化,使得此类无用,除非有人知道解决此问题的方法.

是否有其他可用于此情况的泛型类?

我使用.NET的System.Web.UI.Pair类,但它使用Object作为其类型.如果仅用于类型安全,那么使用Generic类会很好.



1> leppie..:

只需定义一个struct/class.

[Serializable]
public struct KeyValuePair
{
  public K Key {get;set;}
  public V Value {get;set;}
}


可变结构...... :(
@Paddy:了解如何对值类型进行散列并比较平等是必须的
IDictionary现在可以序列化,在4.5中(至少使用JSON)

2> Compile This..:

我不认为Dictionary<>它本身不是XML可序列化的,当我需要通过Web服务发送字典对象时,我最终自己包装Dictionary<>对象并添加支持IXMLSerializable.

/// 
/// Represents an XML serializable collection of keys and values.
/// 
/// The type of the keys in the dictionary.
/// The type of the values in the dictionary.
[XmlRoot("dictionary")]
public class SerializableDictionary : Dictionary, IXmlSerializable
{
    #region Constants

    /// 
    /// The default XML tag name for an item.
    /// 
    private const string DEFAULT_ITEM_TAG = "Item";

    /// 
    /// The default XML tag name for a key.
    /// 
    private const string DEFAULT_KEY_TAG = "Key";

    /// 
    /// The default XML tag name for a value.
    /// 
    private const string DEFAULT_VALUE_TAG = "Value";

    #endregion

    #region Protected Properties

    /// 
    /// Gets the XML tag name for an item.
    /// 
    protected virtual string ItemTagName
    {
        get
        {
            return DEFAULT_ITEM_TAG;
        }
    }

    /// 
    /// Gets the XML tag name for a key.
    /// 
    protected virtual string KeyTagName
    {
        get
        {
            return DEFAULT_KEY_TAG;
        }
    }

    /// 
    /// Gets the XML tag name for a value.
    /// 
    protected virtual string ValueTagName
    {
        get
        {
            return DEFAULT_VALUE_TAG;
        }
    }

    #endregion

    #region Public Methods

    /// 
    /// Gets the XML schema for the XML serialization.
    /// 
    /// An XML schema for the serialized object.
    public XmlSchema GetSchema()
    {
        return null;
    }

    /// 
    /// Deserializes the object from XML.
    /// 
    /// The XML representation of the object.
    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();
    }

    /// 
    /// Serializes this instance to XML.
    /// 
    /// The writer to serialize to.
    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
}


OP根本没有提到词典.问题是关于序列化键/值对.你的答案是相关的,但我认为这有损于基本问题.

3> 小智..:

您将在此MSDN博客文章中找到无法序列化KeyValuePairs的原因

Struct答案是最简单的解决方案,但不是唯一的解决方案.一个"更好"的解决方案是编写一个Serializable的Custom KeyValurPair类.


请注意,DataContractSerializer(与.NET 3.0和WCF一起提供)可以完美地处理KeyValuePair <,>.因此,它不是一般的序列化问题,而是您使用的特定序列化程序的问题(作为MSDN页面的链接建议).

4> GregoryBrad..:
 [Serializable]
 public class SerializableKeyValuePair
    {

        public SerializableKeyValuePair()
        {
        }

        public SerializableKeyValuePair(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public TKey Key { get; set; }
        public TValue Value { get; set; }

    }

推荐阅读
殉情放开那只小兔子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有