解决用序列化方式实现对象拷贝时出的异常解决方法

本文介绍了一个在使用.NET开发的程序集中实现对象拷贝时遇到的问题,并给出了具体的解决方案。该方案解决了从VB调用.NET组件时出现的序列化异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在做一个项目中遇到这样一个问题:
用.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>参考
                /// http://www.chinaaspx.com/archive/dotnet/20028.htm
                /// </remarks>
                /// <author>
                ///  Caveman.lyhu@hotmail.com
                /// </author>
                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);
                }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值