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

前端 未结 10 1379
自闭症患者
自闭症患者 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:36

    Use the DataContractSerializer since it can handle the Key Value Pair.

        public static string GetXMLStringFromDataContract(object contractEntity)
        {
            using (System.IO.MemoryStream writer = new System.IO.MemoryStream())
            {
                var dataContractSerializer = new DataContractSerializer(contractEntity.GetType());
                dataContractSerializer.WriteObject(writer, contractEntity);
                writer.Position = 0;
                var streamReader = new System.IO.StreamReader(writer);
                return streamReader.ReadToEnd();
            }
        }
    
    0 讨论(0)
  • 2020-11-29 02:37

    Just define a struct/class.

    [Serializable]
    public struct KeyValuePair<K,V>
    {
      public K Key {get;set;}
      public V Value {get;set;}
    }
    
    0 讨论(0)
  • 2020-11-29 02:47

    XmlSerializer doesn't work with Dictionaries. Oh, and it has problems with KeyValuePairs too

    http://www.codeproject.com/Tips/314447/XmlSerializer-doesnt-work-with-Dictionaries-Oh-and

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

    You will find the reason why KeyValuePairs cannot be serialised at this MSDN Blog Post

    The Struct answer is the simplest solution, however not the only solution. A "better" solution is to write a Custom KeyValurPair class which is Serializable.

    0 讨论(0)
  • 2020-11-29 02:52
     [Serializable]
     public class SerializableKeyValuePair<TKey, TValue>
        {
    
            public SerializableKeyValuePair()
            {
            }
    
            public SerializableKeyValuePair(TKey key, TValue value)
            {
                Key = key;
                Value = value;
            }
    
            public TKey Key { get; set; }
            public TValue Value { get; set; }
    
        }
    
    0 讨论(0)
  • 2020-11-29 02:52

    A KeyedCollection is a type of dictionary that can be directly serialized to xml without any nonsense. The only issue is that you have to access values by: coll["key"].Value;

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