C#中深拷贝对象的简单方法

  1. class Employee : ICloneable 
  2.     public string IDCode { get; set; } 
  3.     public int Age { get; set; } 
  4.     public Department Department { get; set; } 
  5.     #region ICloneable 成员 
  6.     public object Clone() 
  7.     { 
  8.         using (Stream objectStream = new MemoryStream()) 
  9.         { 
  10.             IFormatter formatter = new BinaryFormatter(); 
  11.             formatter.Serialize(objectStream, this); 
  12.             objectStream.Seek(0, SeekOrigin.Begin); 
  13.             return formatter.Deserialize(objectStream) as Employee; 
  14.         } 
  15.     } 
  16.     #endregion 
  17. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Unity,Lua并没有提供内置的深拷贝函数。但是你可以通过使用C#来实现Lua深拷贝。下面是一个示例代码: ```csharp using UnityEngine; using System.Collections; using System.Collections.Generic; using LuaInterface; public class DeepCopyExample : MonoBehaviour { private LuaState luaState; void Start() { luaState = new LuaState(); luaState.Start(); // 注册一个C#函数给Lua使用 luaState.RegisterFunction("DeepCopy", this, typeof(DeepCopyExample).GetMethod("DeepCopy")); // 执行Lua脚本 luaState.DoString(@" -- 定义一个Lua表 local originalTable = {1, 2, 3, {4, 5, 6}} -- 调用C#函数进行深拷贝 local copiedTable = DeepCopy(originalTable) -- 修改原始表的值 originalTable[1] = 100 -- 打印结果 print('Original Table: ') for i, v in ipairs(originalTable) do print(v) end print('Copied Table: ') for i, v in ipairs(copiedTable) do print(v) end "); } // C#函数,用于实现深拷贝 public LuaTable DeepCopy(LuaTable table) { LuaTable newTable = luaState.NewTable(); foreach (var kvp in table.ToDictTable()) { if (kvp.Value is LuaTable) { // 递归调用深拷贝 newTable[kvp.Key] = DeepCopy(kvp.Value as LuaTable); } else { newTable[kvp.Key] = kvp.Value; } } return newTable; } } ``` 这个示例代码演示了如何在Unity使用Lua和C#来实现深拷贝。在Lua,我们定义了一个原始表`originalTable`,然后通过调用C#函数`DeepCopy`进行深拷贝,将拷贝后的表赋值给`copiedTable`。最后,我们修改了原始表的值,并打印出原始表和拷贝表的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值