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

后端 未结 5 1847
天涯浪人
天涯浪人 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:09

    You have various bugs in your code, otherwise this would work just fine.

    1. In the constructor for ClassA, your are setting an local variable IB, not the object's IB object.
    2. In ClassB, you are casting back to the object concrete class, instead of leaving it alone as the interface type.

    Here is what your code should look like:

    public interface IA 
    { 
        IB InterfaceB { get; set; } 
    }
    
    public interface IB 
    { 
        IA InterfaceA { get; set; } 
        void SetIA(IA value);
    }
    
    [Serializable]
    public class ClassA : IA
    {    
        public IB InterfaceB { get; set; }    
    
        public ClassA()    
        {        
            // Call outside function to get Interface B        
            this.InterfaceB = new ClassB();
    
            // Set IB to have A        
            InterfaceB.SetIA(this);    
        }
    }
    
    [Serializable]
    public class ClassB : IB
    {    
        public IA InterfaceA { get; set; }    
    
        public void SetIA(IA value)    
        {       
            this.InterfaceA = value;    
        }
    }
    
    [STAThread]
    static void Main()
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bin = new BinaryFormatter();
    
        ClassA myA = new ClassA();
    
        bin.Serialize(ms, myA);
    
        ms.Position = 0;
    
        ClassA myOtherA = bin.Deserialize(ms) as ClassA;
    
    
        Console.ReadLine();
    }
    

提交回复
热议问题