DataContractSerializer与抽象(基础)/具体(继承)类

时间:2010-01-13 12:34:15

标签: c# .net serialization

鉴于此代码

public override void Serialize(BaseContentObject obj)
{
    string file = ObjectDataStoreFolder + obj.Slug + ".xml";
    if(obj.GetType() == typeof(Page))
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof Page));
        XmlDictionaryWriter myWriter =
            XmlDictionaryWriter.CreateTextWriter(new FileStream(file, ileMode.CreateNew, FileAccess.Write),
                                             Encoding.UTF8);
        dcs.WriteObject(myWriter, obj);
        myWriter.Close();
    }
    else if(obj.GetType() == typeof(Image))
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof Image));
        ...
        ...
    }
}

有没有办法做这样的事情

DataContractSerializer dcs = new DataContractSerializer(obj.GetType());
// this fails however, compiler error

并删除上面那些if()语句? DataContractSerializer的构造函数需要Type或Namespace,但它不能与obj.GetType()一起使用。

我的班级层次结构如下:

BaseContentClass(abstract)

页面(具体,继承BaseContentClass)

图像(具体,继承BaseContentClass)

...

3 个答案:

答案 0 :(得分:4)

告诉序列化器预期的内容:

[KnownType(typeof(Page))]
[KnownType(typeof(Image))]
[DataContract]
public abstract class BaseContentObject { /* ... */ }

[DataContract]
public class Page : BaseContentObject { /* ... */ }

[DataContract]
public class Image : BaseContentObject { /* ... */ }

然后您可以使用new DataContractSerializer(typeof(BaseContentObject ))来处理所有事情。

答案 1 :(得分:0)

如果您正在讨论此DataContractSerializer,那么以下代码将编译正常:

DataContractSerializer dcs = new DataContractSerializer(obj.GetType());

由于构造函数需要类型参数。

答案 2 :(得分:0)

我更喜欢使用泛型。 帮助器看起来像:

public static string Serialize<T>(T t, IEnumerable<System.Type> types, bool preserveReferences)
    {
        StringBuilder aStringBuilder = new StringBuilder();
        using (StringWriter aStreamWriter = new StringWriter(aStringBuilder))
        {
            DataContractSerializer aDCS;
            using (XmlTextWriter aXmlTextWriter = new XmlTextWriter(aStreamWriter))
            {
                aDCS = new DataContractSerializer( typeof( T ), types, int.MaxValue, false, preserveReferences, null );

                aDCS.WriteObject(aXmlTextWriter, t);
            }
        }
        return aStringBuilder.ToString();
    }

泛型将允许您序列化所需的任何类型,而无需使用if语句。