【问题标题】:How to serialize a class with a complex property using XML serialization in .NET?如何在 .NET 中使用 XML 序列化来序列化具有复杂属性的类?
【发布时间】:2010-10-15 07:48:49
【问题描述】:

我想序列化一个类。在这个类中有一个 Class1 类型的属性,它又具有自己的属性。

public abstract class ComponentBase
{
    [ToSerialize] //An attribute defined my me, indicating whether or not to serialize this property.
    public ComponentArgs Parameters { get; set; }
}

public class ComponentArgs
{
    public string WorkingPath { get; set; }
    public IList<Language> Languages { get; set; }
    public string ComponentOutputPath { get; set; }
}

序列化的信息必须放入Dictionary&lt;string,string&gt;,如

ComponentSettings[str_Name] = str_Value;

读取这个值使用的方法是Reflection

// pinfo: Property Info got via Type.GetProperties();
componentSettings.Add(pinfo.Name, pinfo.GetValue((object)this, null).ToString());

序列化后的信息为:

<Parameters>MS.STBIntl.Pippin.Framework.ComponentArgs</Parameters>

而不是ComponentArgs.WorkingPath的值。

我想到的解决办法是在下面一行追加一个if判断:

componentSettings.Add(pinfo.Name, pinfo.GetValue((object)this, null).ToString());

if(pinfo is ComponentArgs)
    componentSettings.Add(pinfo.Name, pinfo.GetValue(
        (ComponentArgs)this, null).WorkingPath+"\n"+
        LanguageList+"\n"+ //Language list is a concatinated string of all elements in the list.
        (ComponentArgs)this, null).ComponentOutputPath+"\n"+
    );

反序列化时,增加判断值是否包含超过2个“\n”,如果是,则从字符串中提取每个值。

但这种方式看起来很笨拙,更像是一种解决方法。请问有没有更专业的方法?我的审稿人很挑剔,他不会接受这样的解决方案。如果你知道方法,可以分享给我吗?非常感谢。

【问题讨论】:

    标签: c# .net serialization xml-serialization


    【解决方案1】:

    有很多方法可以使用内置序列化。

    最简单和最古老的是 [Serializable] 属性,它告诉 .NET 序列化成员。

    您还可以使用 WCF [DataContract] 属性来序列化内容。

    还有IXMLSerializable 接口,它允许您为您的类实现自定义 XML 读取器和写入器。

    最重要的是,没有必要自己动手——它已经完成了。

    【讨论】:

      猜你喜欢
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      相关资源
      最近更新 更多