【发布时间】:2010-11-28 11:49:39
【问题描述】:
谁能解释为什么会发生以下情况:
当我们在调试模式下序列化文件时,我们可以在调试模式下再次打开它,但不能在运行时打开。 当我们在运行时模式下序列化文件时,我们可以在运行时模式下再次打开它,但不能在调试模式下。
现在我知道你会说:那是因为它们有不同的程序集。 但是我们使用自定义的 Binder,如下所示... 此外,如果我们比较两种类型,“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;
}
【问题讨论】:
标签: c# serialization debugging mode