C#复制实体类
时间: 2025-06-21 07:58:37 浏览: 13
### C# 实体类深拷贝与浅拷贝的实现方式
在C#中,实体类的复制可以通过深拷贝或浅拷贝实现。以下是两种复制方式的具体实现方法及其特点。
#### 浅拷贝
浅拷贝仅复制对象的引用,而不复制引用的对象本身。这意味着如果原始对象包含引用类型成员,则这些成员不会被复制,而是共享相同的引用。浅拷贝可以通过 `MemberwiseClone()` 方法实现[^2]。
```csharp
public class ShallowCopyExample
{
public int Value { get; set; }
public string Name { get; set; }
// 浅拷贝实现
public ShallowCopyExample ShallowCopy()
{
return (ShallowCopyExample)this.MemberwiseClone();
}
}
```
#### 深拷贝
深拷贝不仅复制对象本身,还递归地复制所有引用类型的成员,确保原始对象和副本之间没有任何引用共享。以下是几种常见的深拷贝实现方式:
1. **反射实现深拷贝**
使用反射可以动态访问对象的字段或属性,并递归地进行深拷贝。这种方式适用于复杂对象结构[^3]。
```csharp
public static T DeepCopyWithReflection<T>(T obj)
{
Type type = obj.GetType();
if (obj is string || type.IsValueType)
return obj;
if (type.IsArray)
{
Type elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));
var array = obj as Array;
Array copied = Array.CreateInstance(elementType, array.Length);
for (int i = 0; i < array.Length; i++)
copied.SetValue(DeepCopyWithReflection(array.GetValue(i)), i);
return (T)Convert.ChangeType(copied, obj.GetType());
}
object retval = Activator.CreateInstance(obj.GetType());
PropertyInfo[] properties = obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var property in properties)
{
var propertyValue = property.GetValue(obj, null);
if (propertyValue == null) continue;
property.SetValue(retval, DeepCopyWithReflection(propertyValue), null);
}
return (T)retval;
}
```
2. **序列化实现深拷贝**
序列化将对象转换为字节流,反序列化再将其还原为对象,从而实现深拷贝。常见的序列化方式包括 XML 序列化、二进制序列化和 JSON 序列化[^4]。
- **XML 序列化**
```csharp
public static T DeepCopyWithXmlSerializer<T>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer xml = new XmlSerializer(typeof(T));
xml.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
retval = xml.Deserialize(ms);
ms.Close();
}
return (T)retval;
}
```
- **二进制序列化**
```csharp
public static T DeepCopyWithBinarySerialize<T>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
retval = bf.Deserialize(ms);
ms.Close();
}
return (T)retval;
}
```
- **JSON 序列化(需引用外部库如 Newtonsoft.Json)**
```csharp
public static T DeepCopyWithJsonSerializer<T>(T obj)
{
string json = JsonConvert.SerializeObject(obj);
return JsonConvert.DeserializeObject<T>(json);
}
```
#### 总结
浅拷贝适合简单对象,而深拷贝适合复杂对象。深拷贝可以通过反射、序列化等方式实现,其中序列化方式简单易用,但可能对性能有一定影响[^2]。
---
###
阅读全文
相关推荐


















