2009-09-15 90 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