[英]Serialize property of type object
我有一個可序列化的類,其中包含一些屬性,包括類型為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”具體類型的情況下序列化和反序列化此類?
最好的祝福
在序列化的類中包括所有可能的類型是否可以接受? (這就是消息的含義, 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 );
初始化XmlSerializer時修改您的代碼
XmlSerializer xmlf = new XmlSerializer(testClass.GetType(),new Type [] {typeof(ExtendedParams)});
這將使XmlSerializer知道該類中的其他類型
如異常消息所示,您需要指定派生類型,以便可以識別它:
[Serializable]
[XmlInclude(typeof(ExtendedParams))]
public class SerializeableTestClass
{
[XmlElement(ElementName = "Params")]
public object Params;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.