This question already has answers here:
C# XML serialization of derived classes
                                
                                    (2个答案)
                                
                        
                                6年前关闭。
            
                    
我有以下3个课程:

Class Image : Asset
Class Sound : Asset
Class Video : Asset


一切都可以序列化,但是当我创建此项目时:

Class Master
List<Asset> assets //property


此类的一个实例,例如:

Image i = new Image();
Sound s = new Sound();
Video v = new Video();
Master m =  new Master( new List<Asset>{i,s,v} )


它没有异常序列化
“ InvalidOperationException-生成XML文档时出错”
并在innerException中:{“类型MyApplication.Video不是所期望的。使用XmlInclude或SoapInclude属性来指定静态未知的类型。”}

.. 任何的想法??

最佳答案

XmlInclude类上添加Asset属性:

[XmlInclude(typeof(Video))]
[XmlInclude(typeof(Sound))]
[XmlInclude(typeof(Image))]
public class Asset
{
    ...
}

关于c# - 继承XmlSerializer C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15159931/

10-13 08:28