0

谁能解释为什么会发生以下情况:

当我们在调试模式下序列化文件时,我们可以在调试模式下再次打开它,但不能在运行时打开。当我们在运行时模式下序列化文件时,我们可以在运行时模式下再次打开它,但不能在调试模式下打开。

现在我知道你会说:那是因为他们有不同的程序集。但是我们使用了一个自定义的 Binder,如下所示……此外,如果我们比较两种类型,“bool same = (o.GetType() == c.GetType())”,结果总是“真”? ??

那为什么我们不能打开文件??

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

3 回答 3

4

哦不……我是个白痴……

该类的某些字段在运行时模式下被混淆了......

  • 打头对表*

对不起的人......感谢所有的帮助......

于 2009-09-15T14:44:10.080 回答
1

听起来您正在使用条件编译,例如:

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

如果是这样,您将无法自动反序列化它。

那你有2个选择。

  1. 不要对序列化类型使用条件编译 - 或 -
  2. 通过添加可序列化构造函数来提供自定义序列化程序。
于 2009-09-15T14:34:07.343 回答
0

首先是简单的问题 - 您是否在运行时和调试模式下使用相同的凭据执行?

于 2009-09-15T14:35:33.200 回答