最近在做一个项目中遇到这样一个问题:
用.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);
}