用JSON或者XML等,不存在此问题,或者说相对容易解决此问题。
以下是指特定用Soap来进行序列化和反序列化中碰到的。
在一个程序集中:
class Program
{
static void Main(string[] args)
{
//Serialize();
A a = new A();
string re = Tool.Serialize(a);
Console.WriteLine(re);
var b = Tool.Desrialize<A>(re);
Console.WriteLine(b.ToString());
}
}class Tool
{
public static string Serialize<T>(T obj)
{
try
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Flush();
stream.Close();
//return Convert.ToBase64String(buffer);
string utf8String = Encoding.ASCII.GetString(buffer);
return utf8String;
}
catch (Exception ex)
{
throw new Exception("fail:" + ex.Message);
}
}public static T Desrialize<T>(string str) where T : class
{
T obj = null;try
{
IFormatter formatter = new BinaryFormatter();
byte[] buffer = Encoding.ASCII.GetBytes(str);
//byte[] buffer = Convert.FromBase64String(str);
MemoryStream stream = new MemoryStream(buffer);
obj = (T)formatter.Deserialize(stream);
stream.Flush();
stream.Close();
}
catch (Exception ex)
{
throw new Exception("fail:" + ex.Message);
}
return obj;
}
}[Serializable]
public class A
{
public string a;
}
在另一个程序集中:
class Program
{
static void Main(string[] args)
{
string x = "AAEAAAD/////AQAAAAAAAAAMAgAAAEpDb25zb2xlQXBwbGljYXRpb24zLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUBAAAAFUNvbnNvbGVBcHBsaWNhdGlvbjMuQQEAAAABYQECAAAACgs=";var s = Tool.Desrialize<A>(x);
Console.WriteLine(s.ToString());
}
}class Tool
{
public static string Serialize<T>(T obj)
{
try
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Flush();
stream.Close();
return Convert.ToBase64String(buffer);
}
catch (Exception ex)
{
throw new Exception("fail:" + ex.Message);
}
}public static T Desrialize<T>(string str) where T : class
{
T obj = null;
try
{
IFormatter formatter = new BinaryFormatter();
byte[] buffer = Convert.FromBase64String(str);
MemoryStream stream = new MemoryStream(buffer);
obj = (T)formatter.Deserialize(stream);
stream.Flush();
stream.Close();
}
catch (Exception ex)
{
throw new Exception("fail:" + ex.Message);
}
return obj;
}
}[Serializable]
public class A
{
public string a;
}
无非就是替换其中关于类型程序集信息的替换。
当然,此解决方案的一个问题是,随着每次程序集版本号的修改,代码中的 Replace 部分也要做修改。蛋疼。