我想XML序列化一个对象,该对象具有(以及其他)IModelObject类型的属性(这是一个接口).
public class Example
{
public IModelObject Model { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当我尝试序列化此类的对象时,我收到以下错误:
"无法序列化示例类型的Example.Model,因为它是一个接口."
我知道问题是接口无法序列化.但是,具体的Model对象类型在运行时才会被识别.
用抽象或具体类型替换IModelObject接口并使用XMLInclude继承是可能的,但似乎是一个丑陋的解决方法.
有什么建议?
我有一个课程,如下所示
public class Survey
{
public Survey()
{
SurveyResponses=new List<SurveyResponse>();
}
[Key]
public Guid SurveyId { get; set; }
public string SurveyName { get; set; }
public string SurveyDescription { get; set; }
public virtual ICollection<Question> Questions { get; set; }
public virtual ICollection<SurveyResponse> SurveyResponses { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给了我以下异常
无法序列化'System.Collections.Generic.ICollection类型的成员'SurveyGenerator.Survey.Questions'
当我将ICollection转换为List时,它正确地序列化
由于它是实体框架的POCO,我无法将ICollection转换为List