如下代码先运行一遍:
namespace openMV
{
[Serializable]
class A
{
public A()
{
}
public int a = 1;
public void func()
{
Console.WriteLine('A');
}
public B b = new B();
//public C b = new C();
}
[Serializable]
class B
{
public B()
{
}
public int[] b = new int[5];
//public int c = 4;
public static implicit operator C(B current)
{
C c = new C();
return c;
}
/*public static explicit operator C(B current)
{
C c = new C();
return c;
}*/
}
[Serializable]
class C
{
public C()
{
}
public int[,] c = new int[4, 4];
public void func()
{
Console.WriteLine("CC");
}
}
class Program
{
static void Main(string[] args)
{
//FileStream fs = new FileStream("C:\\testing\\serialize.txt", FileMode.Open);
FileStream fs = new FileStream("C:\\testing\\serialize.txt", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
A a = new A();
//var o = (A)bf.Deserialize(fs);
bf.Serialize(fs, a);
Console.WriteLine("here");
}
}
}
序列化保存到文件之后,然后再运行下面的代码
namespace openMV
{
[Serializable]
class A
{
public A()
{
}
public int a = 1;
public void func()
{
Console.WriteLine('A');
}
//public B b = new B();
public C b = new C();
}
[Serializable]
class B
{
public B()
{
}
public int[] b = new int[5];
//public int c = 4;
public static implicit operator C(B current)
{
C c = new C();
return c;
}
/*public static explicit operator C(B current)
{
C c = new C();
return c;
}*/
}
[Serializable]
class C
{
public C()
{
}
public int[,] c = new int[4, 4];
public void func()
{
Console.WriteLine("CC");
}
}
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream("C:\\testing\\serialize.txt", FileMode.Open);
//FileStream fs = new FileStream("C:\\testing\\serialize.txt", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
//A a = new A();
var o = (A)bf.Deserialize(fs);
//bf.Serialize(fs, a);
Console.WriteLine("here");
}
}
}
这样运行之后会出现类型转化错误,在报错堆栈的最上一层是System.RuntimeType.TryChangeType
,可是我明明已经在class B中定义了转化代码,为什么还会出现这样的问题? 各位大牛求解答如何才能实现在反序列化的时候可以自动转化类型?