这是一个关于序列化绑定器的例子,正如您所要求的那样。这个程序是一个自定义的“序列化”程序,它的参数是一个“序列化绑定器”。
public bool Serialize(string sPath, System.Runtime.Serialization.SerializationBinder serializationBinder) {
bool bSuccessful = false;
if (serializationBinder == null) return false;
try {
using (FileStream fStream = new FileStream(sPath, FileMode.Create)) {
try {
BinaryFormatter bf = new BinaryFormatter();
bf.Binder = serializationBinder;
bf.Serialize(fStream, this._someFoo);
bSuccessful = true;
} catch (System.Runtime.Serialization.SerializationException sEx) {
System.Diagnostics.Debug.WriteLine(sEx.ToString());
bSuccessful = false;
}
}
} catch (System.IO.IOException ioEx) {
System.Diagnostics.Debug.WriteLine(string.Format("[Serialize(...)] - IO EXCEPTION> DETAILS ARE {0}", ioEx.ToString()));
bSuccessful = false;
}
return bSuccessful;
}
public bool Deserialize(string sFileName, System.Runtime.Serialization.SerializationBinder serializationBinder) {
bool bSuccessful = false;
if (!System.IO.File.Exists(sFileName)) return false;
if (serializationBinder == null) return false;
this._foo = new Foo();
try {
using (FileStream fStream = new FileStream(sFileName, FileMode.Open)) {
try {
BinaryFormatter bf = new BinaryFormatter();
bf.Binder = serializationBinder;
this._foo = (Foo)bf.Deserialize(fStream);
bSuccessful = true;
} catch (System.Runtime.Serialization.SerializationException sEx) {
System.Diagnostics.Debug.WriteLine(string.Format("[DeSerialize(...)] - SERIALIZATION EXCEPTION> DETAILS ARE {0}", sEx.ToString()));
bSuccessful = false;
}
}
} catch (System.IO.IOException ioEx) {
System.Diagnostics.Debug.WriteLine(string.Format("[DeSerialize(...)] - IO EXCEPTION> DETAILS ARE {0}", ioEx.ToString()));
bSuccessful = false;
}
return (bSuccessful == true);
}
public class BarBinder : System.Runtime.Serialization.SerializationBinder {
public override Type BindToType(string assemblyName, string typeName) {
Type typeToDeserialize = null;
try {
string assemVer1 = System.Reflection.Assembly.GetExecutingAssembly().FullName;
if (assemblyName.StartsWith("Foo")) {
assemblyName = assemVer1;
typeName = "FooBar" + typeName.Substring(typeName.LastIndexOf("."), (typeName.Length - typeName.LastIndexOf(".")));
}
typeToDeserialize = Type.GetType(String.Format("{0}, {1}", typeName, assemblyName));
} catch (System.Exception ex1) {
throw ex1;
} finally {
}
return typeToDeserialize;
}
}
并且可以这样调用:
_foo.DeSerialize(@"C:\foo.dat", new BarBinder());
这里发生的情况是当实例化'BarBinder'并将其分配给BinaryFormatter的Binder属性时,由于序列化的数据具有类型名称Foo.SomeClass,我们应用了'BarBinder',将类型名称重命名为'FooBar.SomeClass',从而有效地使数据属于另一种类型...