c# - 在 C# 的对象中深度复制 Func

标签 c# .net linq delegates

我正在构建一个单元测试列表,这些单元测试被组织为一个对象列表,每个对象都包含要作为 Func 执行的测试方法。每个对象都有一个在 Func 范围内并由它使用的变量。该变量不作为参数传入。

遍历列表并运行所有测试运行良好,但是否可以从一个对象复制 Func,-破坏对该对象的引用-,并将其分配给一个新对象?我认为这可以通过创建深拷贝以某种方式实现,但我使用 BinaryFormatter 的尝试没有奏效,如有任何提示,我们将不胜感激!

我有一个简化的表单应用程序来说明我的问题:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; using
using System.IO;
using System.Linq; 
using System.Runtime.Serialization.Formatters.Binary; 
using System.Text;
using System.Threading.Tasks; using System.Windows.Forms;

namespace WindowsFormsApplication4 {
 public partial class Form1 : Form
 {
     public Form1()
     {
         InitializeComponent();
     }




     public static object DeepClone(object obj)
     {
         object objResult = null;
         using (MemoryStream ms = new MemoryStream())
         {
             BinaryFormatter bf = new BinaryFormatter();
             bf.Serialize(ms, obj);

             ms.Position = 0;
             objResult = bf.Deserialize(ms);
         }
         return objResult;
     }

     [Serializable]
     public class POCOwithFunc {

         public POCOwithFunc(Func<string> myfunc)
         {
             mqi = myfunc;
         }

         public POCOwithFunc() { }

         public Func<string> mqi;

         public object parm;

     }



     private void button1_Click(object sender, EventArgs e)
     {


         List<POCOwithFunc> testList = new List<POCOwithFunc>();

         for (int x = 0; x < 5; x++)
         {

             var pc = new POCOwithFunc();
             pc.parm = x;
             pc.mqi = delegate()
        {
            var rrq = pc.parm;      
            return "result: " + pc.parm;
        };

             testList.Add(pc);
         }

         String output = "";
         foreach (var test in testList)
         {
             output += test.mqi() + "\r\n";
        }
//output:
//result: 0
//result: 1
//result: 2
//result: 3
//result: 4





         var pocoToBeCopied = testList[2];

         var newpoco = new POCOwithFunc();
         newpoco.parm = 10;
         newpoco.mqi = pocoToBeCopied.mqi;

         var res = newpoco.mqi();  //returns 2


         newpoco = (POCOwithFunc)DeepClone(pocoToBeCopied);  //fails

     }

 } }

最佳答案

这是我第一次听说深度复制委托(delegate)(这是行不通的,因为委托(delegate)(Func 是委托(delegate)的类型)包含对其闭包的引用(它的环境,其中包含该委托(delegate)是的任何变量使用)。

我建议更改参数本身,或者将其作为参数发送(它也有一个委托(delegate)类型:Func<object, string >)。

(而且,我认为你应该考虑重新设计整个东西 :-/)

关于c# - 在 C# 的对象中深度复制 Func,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22151871/

相关文章:

c# - 获取 IIS 应用程序文件系统路径

.net - MSBuild 在 VB.NET lambda 表达式上失败

c# - 通过数据表使用 Linq to GroupBy 和 Case When

c# - 优化还是放弃 LINQ 查询?

asp.net - LINQ 中的匿名类型成员声明符无效

c# - Entity Framework 4 加载并包含合并

c# - 监控和计算 asp.net 网站性能

c# - LINQ 左 JOIN 错误

c# - import c++ unmanaged dll to c#问题

c# - 合并多个列表,每个列表的可变长度为 "popping"个元素