誰能解釋爲什麼下面發生的事情:調試模式下的反序列化?
當我們序列化調試模式下的文件,我們可以再次在調試模式下運行時打開它,但不能。 當我們在運行模式下序列化一個文件時,我們可以在運行模式下再次打開它,但不能在調試模式下打開。
現在我知道你會說:那是因爲他們有不同的程序集。如果我們比較兩種類型,「bool same =(o.GetType()== c.GetType())」,我們總是得到「true」作爲結果???
那麼爲什麼我們不能打開文件?
public class Binder : SerializationBinder {
public override Type BindToType(string assemblyName, string typeName) {
Type tyType = null;
string sShortAssemblyName = assemblyName.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
if (sShortAssemblyName.ToLower() == "debugName")
{
sShortAssemblyName = "runtimeName";
}
foreach (Assembly ayAssembly in ayAssemblies) {
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0]) {
tyType = ayAssembly.GetType(typeName);
break;
}
}
return tyType;
}
}
public static DocumentClass Read(string fullFilePath, bool useSimpleFormat)
{
DocumentClass c = new DocumentClass();
c.CreatedFromReadFile = true;
Stream s = File.OpenRead(fullFilePath);// f.Open(FileMode.Open);
BinaryFormatter b = new BinaryFormatter();
if (useSimpleFormat)
{
b.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
}
b.Binder = new Binder();
try
{
object o = b.Deserialize(s);
c = (DocumentClass)o;
c.CreatedFromReadFile = true;
string objOriginal = o.GetType().AssemblyQualifiedName + "_" + o.GetType().FullName;
string objTarget = c.GetType().AssemblyQualifiedName + "_" + c.GetType().FullName;
bool same = (o.GetType() == c.GetType());
if (c.DocumentTypeID <= 0)
{
throw new Exception("Invalid file format");
}
}
catch(Exception exc)
{
s.Close();
if (!useSimpleFormat)
{
return Read(fullFilePath, true);
}
throw exc;
}
finally
{
s.Close();
}
return c;
}
我們沒有使用條件編譯...... 我剛剛搜查了整個VS項目,無處是有「#如果DEBUG「行... 謝謝你可能的解決方案雖然.. – 2009-09-15 14:39:54