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

后端 未结 5 1813
天涯浪人
天涯浪人 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条回答
  •  -上瘾入骨i
    2021-01-05 02:16

    Interface properties are not serializable. However, fields that reference those properties (in the subclass) are.

    You'll need to do something like this:

    [Serializable]
    public class ClassA : IA
    {
        private IB _interfaceB;
        public IB InterfaceB { get { return _interfaceB; } set { _interfaceB = value; } }
    
        public ClassA()
        {
            // Call outside function to get Interface B
            IB interfaceB = Program.GetInsanceForIB();
    
            // Set IB to have A
            interfaceB.SetIA(this);
        }
    }
    
    [Serializable]
    public class ClassB : IB
    {
        private IA _interfaceA;
        public IA InterfaceA { get { return _interfaceA; } set { _interfaceA = value; } }
    
        public void SetIA(IA value)
        {
            this.InterfaceA = value as ClassA;
        }
    }
    

提交回复
热议问题