无法深度复制'List <t>'C#</t>

时间:2010-01-04 18:11:19

标签: c# .net

我在深度复制列表方面遇到了麻烦。

我的主窗口名为Form1,其实例为System.Collections.Generic.List<T>,我希望能够通过单独的SettingsForm提供编辑此列表的功能,其中包含“确定”和“取消” - 按钮。如果用户按下“OK”,则对列表的更改将生效,但如果用户按下“取消”,则(自然地)必须取消所有更改。要实现此目的,SettingsForm用于制作列表的深层副本,对用户请求对复制列表进行任何更改,然后 - 如果用户按下“确定” - 将编辑后的副本传回{{1}替换原文。

要制作深层副本,我使用Form1 - MemoryStream解决方案建议here我的问题是,当我第二次调用BinaryFormatter时,我得到了一个我的深拷贝函数的异常,指出SettingsForm不可序列化。好像我已经将null传递给了深拷贝函数,但我已经注意不要了。

好吧,如果你已经读过这篇文章了,我猜你想要看一些代码,所以我们走了;首先是null的相关部分:

Form1



然后public partial class Form1 : Form { ... private List<ScriptListEntry> scriptList; ... public Form1() { InitializeComponent(); ... // Create an empty script list scriptList = new List<ScriptListEntry>(); ... } ... private void toolStripButton2_Click(object sender, EventArgs e) { /* Will display 'SettingsForm' to allow the user to change the program * settings. */ ... SettingsForm sform = new SettingsForm(); ... sform.setScriptList(scriptList); sform.ShowDialog(); }

SettingsForm



最后,下面第11行的深拷贝机器会抛出异常

public partial class SettingsForm : Form
{
...

private List<ScriptListEntry> scriptList;
private List<ScriptListEntry> scriptListWorkingCopy;

public SettingsForm()
{
  InitializeComponent();

  scriptList = null;
  scriptListWorkingCopy = null;
  ...
}

public void setScriptList(List<ScriptListEntry> scriptList_)
{
  // Keep a reference to the original list
  scriptList = scriptList_;

  if (null != scriptList_)
  {
    if (0 != scriptList_.Count)
    {
      /* Make a working copy because settings made in 'SettingsForm' must
       * not be committed until OK-button is clicked. 'DeepCopy' does not
       * work if object to be copied is 'null' or the list is empty. 
       */
      scriptListWorkingCopy = DeepCopy<List<ScriptListEntry>>.deepCopy(scriptList_);

      ...
    }
  }
  else
  ...
}

...

// OK-button
private void button1_Click(object sender, EventArgs e)
{
  ...

  // Update the script list
  if (null != scriptList)
  {
    scriptList.Clear();
    scriptList.AddRange(scriptListWorkingCopy);
  }
  else
  ...
}

第一次创建列表工作得很好(我已经验证了它的内容)但是当我第二次尝试调出'SettingsForm'时会发生异常。例外是'System.Runtime.Serialization.SerializationException' - “PublicKeyToken = null'未标记为可序列化”

感谢您阅读!

1 个答案:

答案 0 :(得分:2)

您已修剪错误消息文本 - PublicKeyToken=null是类型的程序集限定名称的结尾 - 它应该类似于Foo.Bar, Baz, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null - 即类Foo.Bar in版本1.2.3.4的汇编Baz,文化中立,未签名。在您的情况下,错误是所述类型不归因为[Serializable]

相关问题