将泛型与 XmlSerializer 一起使用
在 C# 中使用 XML 序列化时,我使用如下代码:(
public MyObject LoadData()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));
using (TextReader reader = new StreamReader(settingsFileName))
{
return (MyObject)xmlSerializer.Deserialize(reader);
}
}
以及类似的反序列化代码)。
它需要铸造并且不太好。有没有办法直接在 .NET Framework 中使用带有序列化的泛型?也就是说要写这样的东西:
public MyObject LoadData()
{
// Generics here.
XmlSerializer<MyObject> xmlSerializer = new XmlSerializer();
using (TextReader reader = new StreamReader(settingsFileName))
{
// No casts nevermore.
return xmlSerializer.Deserialize(reader);
}
}
When using XML serialization in C#, I use code like this:
public MyObject LoadData()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));
using (TextReader reader = new StreamReader(settingsFileName))
{
return (MyObject)xmlSerializer.Deserialize(reader);
}
}
(and similar code for deserialization).
It requires casting and is not really nice. Is there a way, directly in .NET Framework, to use generics with serialization? That is to say to write something like:
public MyObject LoadData()
{
// Generics here.
XmlSerializer<MyObject> xmlSerializer = new XmlSerializer();
using (TextReader reader = new StreamReader(settingsFileName))
{
// No casts nevermore.
return xmlSerializer.Deserialize(reader);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
除了@Oded之外,您还可以将方法设为通用 同样:
这样你就不需要使整个类通用,你可以像这样使用它:
An addition to @Oded, you can make the method Generic aswell:
This way you don't need to make the whole class generic and you can use it like this:
使您的序列化类/方法通用:
Make your serialization class/method generic:
一个简单的通用包装器:
这会将您的对象序列化到 bin/debug 文件夹:
A simple generic wrapper:
This will serialize your object to the bin/debug folder:
试试这个。
Try this.
总是对我有用
,这适用于反序列化:
always work's for me
and this is for Deserialize: