解決用序列化方式實現對象拷貝時出的異常解決方法
最近在做一個項目中遇到這樣一個問題:
用.NET(C#)上開發一個程序集(.dll形式),其中用到序列化方式實現對象拷貝, 在VB中進行調用,在運行到對象拷貝模塊時報出這樣的一個異常:
System.Runtime.Serialization.SerializationException: Cannot find the assembly SimpleAsm, Version=xxxx, Culture=xxxx, PublicKeyToken=xxxx.
通過參考網上一些資料,終於將問題解決.
其中核心代碼如下:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
…
…
/// <summary>
/// 對象拷貝
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
/// <remarks>參考
/// </remarks>
public static object DeepClone(object source)
{
if (source==null) return null;
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, source);
stream.Position = 0;
System.Threading.Thread.GetDomain().AssemblyResolve += new ResolveEventHandler(SignUtility_AssemblyResolve);//關鍵
object obj = formatter.Deserialize(stream);
System.Threading.Thread.GetDomain().AssemblyResolve -= new ResolveEventHandler(SignUtility_AssemblyResolve);//關鍵
return obj;
}
}
private static System.Reflection.Assembly SignUtility_AssemblyResolve(object sender, ResolveEventArgs args)
{
string[] strProps = args.Name.Split(new char[] {','});
string m_codebase = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String strPath = string.Format(@"{0}/{1}.dll",m_codebase,strProps[0]);
return System.Reflection.Assembly.LoadFrom(strPath);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.