![](/img/trans.png)
[英]c# With Unity and LitJSON Getting an Invalid Cast Exception when trying to de-serialize back from JSONData object
[英]C# Exception when trying to serialize a dynamic derived object
我有以下课程:
[XmlInclude(typeof(Cat))]
[XmlInclude(typeof(Dog))]
[XmlInclude(typeof(Cow))]
[Serializable]
public abstract class Animal
{
public string Name { get; set; }
}
public class Cow : Animal
{
public Cow(string name) { Name = name; }
public Cow() { }
}
public class Dog : Animal
{
public Dog(string name) { Name = name; }
public Dog() { }
}
public class Cat : Animal
{
public Cat(string name) { Name = name; }
public Cat() {}
}
以及以下代码段:
var animalList = new List<Animal>();
Type type = AnimalTypeBuilder.CompileResultType("Elephant", propertiesList);
var elephant = Activator.CreateInstance(type);
animalList.Add(new Dog());
animalList.Add(new Cat());
animalList.Add(new Cow());
animalList.Add((Animal)elephant);
using (var writer = new System.IO.StreamWriter(fileName))
{
var serializer = new XmlSerializer(animalList.GetType());
serializer.Serialize(writer, animalList);
writer.Flush();
}
当我尝试序列化此列表时,出现错误:
System.InvalidOperationException:不需要类型大象。 使用XmlInclude或SoapInclude属性可以指定静态未知的类型。
起初,我还为Cat
, Cow
和Dog
对象获得了此异常,并通过将[XmlInclude(typeof(...))]
到它们的类中来解决了该异常,但是对于动态派生,我找不到类似的解决方案类型,因为此属性是在编译时设置的。
您可以在运行时通过构造函数告诉XmlSerializer
有关所需的其他类型。 例如:
var serializer = new XmlSerializer(animalList.GetType(), new[] { typeof(Elephant) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.