我如何序列化有一个接口作为属性的对象? [英] How can I serialize an object that has an interface as a property?
本文介绍了我如何序列化有一个接口作为属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个接口,IA和IB。
I have 2 interfaces IA and IB.
public interface IA
{
IB InterfaceB { get; set; }
}
public interface IB
{
IA InterfaceA { get; set; }
void SetIA(IA value);
}
每个接口引用等。
我想序列化ClassA的定义如下:
I am trying to serialize ClassA as defined below.
[Serializable]
public class ClassA : IA
{
public IB InterfaceB { get; set; }
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
{
public IA InterfaceA { get; set; }
public void SetIA(IA value)
{
this.InterfaceA = value as ClassA;
}
}
我得到一个错误,当我尝试过序列化,因为2属性界面。我想序列化的属性。
I get an error when I try too serialize because the 2 properties are interfaces. I want to serialize the properties.
我将如何解决此得到什么?
How would I get around this?
我需要在引用每个接口到另一个。我需要能够序列化类来回。
I need to have references in each interface to the other. And I need to be able to serialize the class back and forth.
推荐答案
您在你的代码的各种错误,否则这会工作得很好。
You have various bugs in your code, otherwise this would work just fine.
- 在构造
ClassA的
,你要设置的地方变量IB,而不是对象的IB对象。 - 在
ClassB的
,你是铸造回对象具体类,而不是把的单独的接口类型
- In the constructor for
ClassA
, your are setting an local variable IB, not the object's IB object. - 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();
}
这篇关于我如何序列化有一个接口作为属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文