How can I serialize an object that has an interface as a property?

后端 未结 5 1846
天涯浪人
天涯浪人 2021-01-05 01:45

I have 2 interfaces IA and IB.

public interface IA
{
    IB InterfaceB { get; set;  }
}

public interface IB
{
    IA InterfaceA { get; set;  }

    void Set         


        
5条回答
  •  轮回少年
    2021-01-05 02:10

    Implement ISerializable on your objects to control the serialization.

    [Serializable]
    public class ClassB : IB, ISerializable
    {
      public IA InterfaceA { get; set; }
    
      public void SetIA(IA value)
      {
         this.InterfaceA = value as ClassA;
      }
    
      private MyStringData(SerializationInfo si, StreamingContext ctx) {
        Type interfaceAType = System.Type.GetType(si.GetString("InterfaceAType"));
        this.InterfaceA = si.GetValue("InterfaceA", interfaceAType);
      }
    
      void GetObjectData(SerializationInfo info, StreamingContext ctx) {
        info.AddValue("InterfaceAType", this.InterfaceA.GetType().FullName);
        info.AddValue("InterfaceA", this.InterfaceA);
      }
    }
    

提交回复
热议问题