序列化和反序列化在C# [英] serialization and Deserialization in c#
问题描述
我面临的一个问题,而这样做的序列化和放大器;反序列化使用C#。基本上我使用的DataContractSerializer序列化对象
I am facing a problem while doing serialization & deserialization using c#. Basically i am using DataContractSerializer to serialize an object.
下面是我的序列化代码:
Here is my serialization code:
var serializer = new DataContractSerializer(typeof(ProjectSetup));
string xmlString;
using (var sw = new StringWriter())
{
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
serializer.WriteObject(writer, DALProjectSetup);
writer.Flush();
xmlString = sw.ToString();
}
}
System.Web.HttpContext.Current.Session["ProjectSetup"] = xmlString;
这是正常工作,但现在我需要帮助如何反序列化上面。
This is working correctly but now I need help on how to deserialize the above.
推荐答案
瓦伦丁的回答显示了如何反序列化
Valentin's answer shows you how to deserialize.
回复您的评论:
我收到此错误:一开始只是类型的集合System.Collections.Hashtable'返回空值。输入流中包含如果实例为null,它不能添加采集项目。
i am getting this error: The get-only collection of type 'System.Collections.Hashtable' returned a null value. The input stream contains collection items which cannot be added if the instance is null.
(注意的HashTable
通常将是值得避免,太)
(note HashTable
would generally be worth avoiding, too)
这是因为的DataContractSerializer
的不运行一个构造器的,所以如果你有:
That is because DataContractSerializer
does not run a constructor, so if you have:
private readonly HashTable myData = new HashTable();
[DataMember]
public HashTable MyData { get { return myData; } }
或
private readonly HashTable myData;
[DataMember]
public HashTable MyData { get { return myData; } }
public MyType() {
myData = new HashTable();
}
然后 myData的
将总是空
反序列化。有几个思路:
then myData
will always be null
for deserialization. A few ideas:
首先,尝试加入私人集;例如:
First, try adding a private set; for example:
[DataMember]
public HashTable MyData { get; private set; }
public MyType() {
MyData = new HashTable();
}
否则,你可以使用之前,反序列化回调:
Otherwise, you could use a before-deserialization callback:
[OnDeserializing]
void OnSerializing(StreamingContext ctx) {
myData = new HashTable();
}
private HashTable myData = new HashTable();
[DataMember]
public HashTable MyData { get { return myData; } }
或者:使物业更加智能化:
Or: make the property more intelligent:
private HashTable myData;
[DataMember]
public HashTable MyData { get { return myData ?? (myData = new HashTable()); } }
这篇关于序列化和反序列化在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!