序列化对象的属性

时间:2014-04-24 06:48:22

标签: c# .net xml serialization

我有一个可序列化的类,它包含一些属性,包括object类型的变量。我希望我的类能够包含不同的(当然可序列化的)对象。问题是,我在序列化过程中遇到异常:

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

我为此问题创建了一个小样本:

class Program
{
    static void Main(string[] args)
    {
        SerializeableTestClass testClass = new SerializeableTestClass();

        testClass.Params = new ExtendedParams();

        MemoryStream ms = new MemoryStream();
        XmlSerializer xmlf = new XmlSerializer(testClass.GetType());
        xmlf.Serialize(ms, testClass);
        ms.Capacity = (int)ms.Length;
        ms.Close();
        byte[] array =  ms.GetBuffer();
    }
}

[Serializable]
public class SerializeableTestClass
{
    [XmlElement(ElementName = "Params")]
    public object Params;
}

[Serializable]
public class ParamsBase
{
    [XmlElement(ElementName = "SomeValue")]
    public Int32 SomeValue;
}

[Serializable]
public class ExtendedParams : ParamsBase
{
    [XmlElement(ElementName = "SomeNewValue")]
    public Int32 SomeNewValue;
}

是否有可能序列化和反序列化此类而不指定" Params"的具体类型。 ???

祝你好运

3 个答案:

答案 0 :(得分:2)

在序列化的类中包含所有可能的类型是否可以接受? (这就是消息的含义,ExtendedParams没有包含类型信息。)

您可以将其添加到XmlSerializeritself中,或将其包含在主要类中:

[Serializable]
[XmlInclude(typeof(ParamsBase))]
[XmlInclude(typeof(ExtendedParams))]
public class SerializeableTestClass
{
    [XmlElement(ElementName = "Params")]    
    public object Params;
}

但如果您不了解所有类型,请动态序列化:

//static: XmlSerializer xmlf = new XmlSerializer(testClass.GetType(),new Type[]{typeof(ExtendedParams)});

//dynamic:
Type[] extratypes = testClass.Params == null ? null : new Type[] { testClass.Params.GetType() };
XmlSerializer xmlf = new XmlSerializer(testClass.GetType(), extratypes );

答案 1 :(得分:1)

初始化XmlSerializer时修改代码

 XmlSerializer xmlf = new XmlSerializer(testClass.GetType(),new Type [] {typeof(ExtendedParams)});

这将让XmlSerializer了解类

中的其他类型

答案 2 :(得分:0)

正如异常消息所示,您需要指定派生类型,以便可以识别它:

[Serializable]
[XmlInclude(typeof(ExtendedParams))]
public class SerializeableTestClass
{
    [XmlElement(ElementName = "Params")]
    public object Params;
}