用接口序列化子集合

本文关键字:子集合 序列化 接口 | 更新日期: 2023-09-27 17:49:45

我有一个这样的界面

public interface IA{
    IEnumerable<IB> Items {get;set;}
}
public interface IB{
    int ID {get;set;}
}

如果我尝试序列化接口,我会得到一个错误

Cannot serialize interface

如果创建接口的具体版本,则不能创建集合的具体版本。

public class classA:IA{
   public IEnumerable<B> Items {get;set;}  //this doesn't match the interface
}

但是如果我做下面的操作我们仍然有序列化问题

public class classA:IA{
   public IEnumerable<IB> Items {get;set;}
}

用接口序列化子集合

您确定要一个接口吗?泛型可以帮助您序列化不同类型的IEnumerables。

Serializable属性不能从基类继承。将其添加到子类并重试。

你不能序列化接口——你知道,计算机没有说谎;-)

尝试使用具体类型。

List<object>或数组代替IEnumerable<IB>

HTH