2009-09-15 44 views
0

誰能解釋爲什麼下面發生的事情:調試模式下的反序列化?

當我們序列化調試模式下的文件,我們可以再次在調試模式下運行時打開它,但不能。 當我們在運行模式下序列化一個文件時,我們可以在運行模式下再次打開它,但不能在調試模式下打開。

現在我知道你會說:那是因爲他們有不同的程序集。如果我們比較兩種類型,「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; 
    } 

回答

4

哦,不......我是個白癡......

一些類的字段的運行模式會被混淆...

  • 命中前往臺*

對不起人民......感謝所有幫助...

1

這聽起來像你正在使用條件編譯,如:

class Foo { 
#if DEBUG 
    int Bar; 
#endif 
} 

如果是這樣,您將無法自動反序列化。

然後您有2個選擇。

  1. 不使用序列化的類型條件編譯 - 或 -
  2. 通過添加序列化的構造函數提供一個自定義序列。
+0

我們沒有使用條件編譯...... 我剛剛搜查了整個VS項目,無處是有「#如果DEBUG「行... 謝謝你可能的解決方案雖然.. – 2009-09-15 14:39:54

0

第一個簡單問題 - 您是否在運行時和調試模式下使用相同的憑據執行?

+0

我不知道我是否完全理解你的意思,但我們正在運行和調試爲同一個Windows用戶... – 2009-09-15 14:41:57