我目前正在为我的DataSet使用包装类,以实现自定义序列化。我想使用DataContractSerializer
(更像是必须使用它)但仍然支持自定义序列化。问题是[DataContract]
和[Serializable]
属性看起来并不那么顺利......我怎样才能覆盖序列化,并支持 BOTH DataContract& ISerializable序列化?
包装器DataSet类的代码放在这里:
[Serializable()]
[System.Runtime.InteropServices.ComVisible(false)]
public class TestDatasetWrapper : TestDataSet, ISerializable
{
public TestDatasetWrapper()
: base()
{}
protected TestDatasetWrapper(SerializationInfo info, StreamingContext context)
{
SerializationHelper.DeserializeTypedDataSet(info, this);
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializationHelper.AddTypedDataSetObjectData(info, this);
}
}
谢谢!
答案 0 :(得分:13)
DataContractAttribute和SerializableAttribute都可以一起使用。这里的奖励是,您不需要使用单独的序列化器。 DataContractSerialzer是一个XmlObjectSerializer,它本身支持[Serializable]。例如:
[Serializable]
public class TestClass
{
public string Name { get; set; }
}
{
var formatter = new DataContractSerializer(typeof(TestClass));
using (var stream = new MemoryStream())
{
var instance = new TestClass { Name = "Matt" };
formatter.WriteObject(stream, instance);
stream.Seek(0, SeekOrigin.Begin);
var second = (TestClass) formatter.ReadObject(stream);
Console.WriteLine(second.Name);
}
}
输出:“马特”
使用一个SerializableAttribute属性,我们可以使用DataContractSerializer成功序列化和反序列化对象...
使用ISerializable,我们可以做同样的事情:
[Serializable]
public class TestClass2 : ISerializable
{
public TestClass2() { }
protected TestClass2(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("name").ToUpper();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("name", Name);
}
public string Name { get; set; }
}
{
var formatter = new DataContractSerializer(typeof(TestClass2));
using (var stream = new MemoryStream())
{
var instance = new TestClass2 { Name = "Matt" };
formatter.WriteObject(stream, instance);
stream.Seek(0, SeekOrigin.Begin);
var second = (TestClass2)formatter.ReadObject(stream);
Console.WriteLine(second.Name);
}
}
输出:“MATT”
使用DataContractAttribute:
[DataContract, Serializable]
public class TestClass3
{
public int Age { get; set; }
[DataMember]
public string Name { get; set; }
}
{
var formatter = new DataContractSerializer(typeof(TestClass3));
using (var stream = new MemoryStream())
{
var instance = new TestClass3 { Name = "Matt", Age = 26 };
formatter.WriteObject(stream, instance);
stream.Seek(0, SeekOrigin.Begin);
var second = (TestClass3)formatter.ReadObject(stream);
Console.WriteLine(second.Name);
Console.WriteLine(second.Age);
}
}
输出:“马特”
输出:0
当DataContractSerializer遇到带有DataContractAttribute的类型时,它将使用它而不是将序列化传递给它的基类型,后者处理SerializableAttribute和ISerializable接口。
如果您遇到问题,是序列化还是反序列化,或两者兼而有之?