How do you do a deep copy of an object in .NET?(如何在 .NET 中对对象进行深层复制?)
问题描述
我想要一个真正的深拷贝.在 Java 中,这很容易,但在 C# 中如何做到这一点?
I want a true deep copy. In Java, this was easy, but how do you do it in C#?
推荐答案
重要提示
BinaryFormatter 已被弃用,2023 年 11 月后将不再在 .NET 中提供.请参阅 BinaryFormatter 淘汰策略
Important Note
BinaryFormatter has been deprecated, and will no longer be available in .NET after November 2023. See BinaryFormatter Obsoletion Strategy
我已经看到了几种不同的方法,但我使用了一个通用的实用方法:
I've seen a few different approaches to this, but I use a generic utility method as such:
public static T DeepClone<T>(this T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
注意事项:
您的类必须标记为
[Serializable]
才能正常工作.
您的源文件必须包含以下代码:
Your source file must include the following code:
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
这篇关于如何在 .NET 中对对象进行深层复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 .NET 中对对象进行深层复制?


基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01