将泛型与 XmlSerializer 一起使用

发布于 2024-08-29 14:40:30 字数 701 浏览 7 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

寂寞美少年 2024-09-05 14:40:30

除了@Oded之外,您还可以将方法设为通用 同样:

public T ConvertXml<T>(string xml)
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(new StringReader(xml));
}

这样你就不需要使整个类通用,你可以像这样使用它:

var result = ConvertXml<MyObject>(source);

An addition to @Oded, you can make the method Generic aswell:

public T ConvertXml<T>(string xml)
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(new StringReader(xml));
}

This way you don't need to make the whole class generic and you can use it like this:

var result = ConvertXml<MyObject>(source);
北方的巷 2024-09-05 14:40:30

使您的序列化类/方法通用:

public T LoadData<T>()
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        return (T)xmlSerializer.Deserialize(reader);
    }
}

Make your serialization class/method generic:

public T LoadData<T>()
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (TextReader reader = new StreamReader(settingsFileName))
    {
        return (T)xmlSerializer.Deserialize(reader);
    }
}
温柔一刀 2024-09-05 14:40:30

一个简单的通用包装器:

public class GenericSerializer<T> : XmlSerializer
{
    public GenericSerializer(): base(typeof(T)) { }
}

这会将您的对象序列化到 bin/debug 文件夹:

static void Main(string[] args)
{
   Person p = new Person { Name = "HelloWorld" };
   GenericSerializer<Person> ser = new GenericSerializer<Person>();
   ser.Serialize(new StreamWriter("person.xml"), p);
}

A simple generic wrapper:

public class GenericSerializer<T> : XmlSerializer
{
    public GenericSerializer(): base(typeof(T)) { }
}

This will serialize your object to the bin/debug folder:

static void Main(string[] args)
{
   Person p = new Person { Name = "HelloWorld" };
   GenericSerializer<Person> ser = new GenericSerializer<Person>();
   ser.Serialize(new StreamWriter("person.xml"), p);
}
七颜 2024-09-05 14:40:30

试试这个。

public class SerializeConfig<T> where T : class
{
    public static void Serialize(string path, T type)
    {
        var serializer = new XmlSerializer(type.GetType());
        using (var writer = new FileStream(path, FileMode.Create))
        {
            serializer.Serialize(writer, type);
        }
    }

    public static T DeSerialize(string path)
    {
        T type;
        var serializer = new XmlSerializer(typeof(T));
        using (var reader = XmlReader.Create(path))
        {
            type = serializer.Deserialize(reader) as T;
        }
        return type;
    }
}

Try this.

public class SerializeConfig<T> where T : class
{
    public static void Serialize(string path, T type)
    {
        var serializer = new XmlSerializer(type.GetType());
        using (var writer = new FileStream(path, FileMode.Create))
        {
            serializer.Serialize(writer, type);
        }
    }

    public static T DeSerialize(string path)
    {
        T type;
        var serializer = new XmlSerializer(typeof(T));
        using (var reader = XmlReader.Create(path))
        {
            type = serializer.Deserialize(reader) as T;
        }
        return type;
    }
}
素手挽清风 2024-09-05 14:40:30

总是对我有用

  public static string ObjectToXmlSerialize<T>(T dataToSerialize)
    {
        try
        {
            var stringwriter = new System.IO.StringWriter();
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
        catch (Exception ex)
        {
        }
        return null;
    }

,这适用于反序列化:

  public static T XmlDeserializeToObject<T>(string xmlText)
    {
        try
        {
            var stringReader = new System.IO.StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
        catch (Exception ex)
        {
        }
        return default(T);
    }

always work's for me

  public static string ObjectToXmlSerialize<T>(T dataToSerialize)
    {
        try
        {
            var stringwriter = new System.IO.StringWriter();
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
        catch (Exception ex)
        {
        }
        return null;
    }

and this is for Deserialize:

  public static T XmlDeserializeToObject<T>(string xmlText)
    {
        try
        {
            var stringReader = new System.IO.StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
        catch (Exception ex)
        {
        }
        return default(T);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文