由于从兰斯·麦卡锡上面的代码:
[DataContract]
public class Foo
{
[DataMember]
public string SomeText { get; set; }
// ....
[IgnoreDataMember]
public string FizzBuzz { get; set; }
}
此外,你可以用我自己的分机(!更改的MemoryStream到FILESTREAM如果您需要将其保存到文件,而不是字符串):
public static class Extensions
{
public static string Serialize<T>(this T obj)
{
var ms = new MemoryStream();
// Write an object to the Stream and leave it opened
using (var writer = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, ownsStream: false))
{
var ser = new DataContractSerializer(typeof(T));
ser.WriteObject(writer, obj);
}
// Read serialized string from Stream and close it
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
ms.Position = 0;
return reader.ReadToEnd();
}
}
public static T Deserialize<T>(this string xml)
{
var ms = new MemoryStream();
// Write xml content to the Stream and leave it opened
using (var writer = new StreamWriter(ms, Encoding.UTF8, 512, leaveOpen: true))
{
writer.Write(xml);
writer.Flush();
ms.Position = 0;
}
// Read Stream to the Serializer and Deserialize and close it
using (var reader = XmlDictionaryReader.CreateTextReader(ms, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null))
{
var ser = new DataContractSerializer(typeof(T));
return (T)ser.ReadObject(reader);
}
}
}
,然后只用这些的一些推广:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestSerializer()
{
var obj = new Foo()
{
SomeText = "Sample String",
SomeNumber = 135,
SomeDate = DateTime.Now,
SomeBool = true,
};
// Try to serialize to string
string xml = obj.Serialize();
// Try to deserialize from string
var newObj = xml.Deserialize<Foo>();
Assert.AreEqual(obj.SomeText, newObj.SomeText);
Assert.AreEqual(obj.SomeNumber, newObj.SomeNumber);
Assert.AreEqual(obj.SomeDate, newObj.SomeDate);
Assert.AreEqual(obj.SomeBool, newObj.SomeBool);
}
}
祝你好运队友。
为什么反对票,无评论? – John
我没有downvote,但这里没有问题,所以我可以明白为什么有人会。 –
公平点。编辑包含一个问题。 – John