【发布时间】: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<string,string>,如
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