为什么.NET中没有XML可序列化的字典?

我需要一个XML可序列化的字典。实际上,我现在有两个非常不同的程序,需要一个。看到.NET没有它,我感到非常惊讶。我在其他地方问了这个问题,并得到了讽刺的回答。我不明白为什么这是一个愚蠢的问题。

鉴于各种.NET功能对XML序列化的依赖性如何,有人可以启发我,为什么没有XML可序列化的字典。希望您也可以解释为什么有些人认为这个愚蠢的问题。我想我必须缺少一些基本知识,希望您能够填补空白。


哔哔one
浏览 401回答 3
3回答

Cats萌萌

关于XML序列化的问题不仅在于创建字节流。它还与创建此字节流将针对其进行验证的XML模式有关。XML Schema中没有很好的方法来表示字典。您能做的最好的就是证明有一个唯一的钥匙。您始终可以创建自己的包装器,例如“序列化词典的一种方法”。

慕尼黑5688855

我知道以前已经回答过这个问题,但是由于我有一个非常简洁的方法(代码)来使用DataContractSerializer类(由WCF使用,但可以并且应该在任何地方使用)进行IDictionary序列化,所以我不能拒绝在这里提供它:public static class SerializationExtensions{&nbsp; &nbsp; public static string Serialize<T>(this T obj)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var serializer = new DataContractSerializer(obj.GetType());&nbsp; &nbsp; &nbsp; &nbsp; using (var writer = new StringWriter())&nbsp; &nbsp; &nbsp; &nbsp; using (var stm = new XmlTextWriter(writer))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; serializer.WriteObject(stm, obj);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return writer.ToString();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static T Deserialize<T>(this string serialized)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var serializer = new DataContractSerializer(typeof(T));&nbsp; &nbsp; &nbsp; &nbsp; using (var reader = new StringReader(serialized))&nbsp; &nbsp; &nbsp; &nbsp; using (var stm = new XmlTextReader(reader))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (T)serializer.ReadObject(stm);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}尽管我尚未对其进行测试,但它在.NET 4中可以完美地工作,并且在.NET 3.5中也可以工作。更新:它不支持 .NET Compact Framework(甚至Windows Phone 7的NETCF 3.7也不适用)DataContractSerializer!我将流式传输到字符串是因为它对我来说更方便,尽管我可以将较低级别的序列化引入Stream,然后用它来序列化为字符串,但是我倾向于只在需要时进行泛化(就像过早的优化是邪恶的一样) ,这是过早的概括...)用法很简单:// dictionary to serialize to stringDictionary<string, object> myDict = new Dictionary<string, object>();// add items to the dictionary...myDict.Add(...);// serialization is straight-forwardstring serialized = myDict.Serialize();...// deserialization is just as simpleDictionary<string, object> myDictCopy =&nbsp;&nbsp; &nbsp; serialized.Deserialize<Dictionary<string,object>>();myDictCopy将是myDict的逐字记录副本。您还将注意到,提供的通用方法将能够序列化任何类型(据我所知),因为它不仅限于IDictionary接口,它实际上可以是任何通用类型T。希望它可以帮助某个人!
打开App,查看更多内容
随时随地看视频慕课网APP