C#从对象列表中复制对象并粘贴到列表中的其他位置

时间:2016-12-13 12:56:27

标签: c# list object copy paste

我有一个类动物,并列出了这个类。

List<Animal> animalLibrary = new List<Animal>();

我希望复制并粘贴此列表中的对象,并将其放在列表中的其他位置。所以,我想制作一个animalLibrary [c]的副本,然后将这个对象粘贴到animalLibrary []中的另一个位置。

使用此复制,似乎工作。

Clipboard.SetDataObject(animalLibrary[c]);

使用此方法粘贴,但不断显示msgbox。

IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Serializable))
{
    animalLibrary.Insert(c, (Animal)iData.GetData("Animal"));
}
else
{
    MessageBox.Show("Could not paste the data");
}
Get_Data();
Load_Data();

获取NullReferenceException从强制插入时显示数据。

编辑: 接受了妈妈的建议并创建了一个Animal类的副本并使用animalLibrary.Insert(index + 1,a)&#39; a&#39;来粘贴它。是动物的副本。

1 个答案:

答案 0 :(得分:0)

这是您可以将项目从列表移动到同一列表中的另一个“位置”:

var list = new List<int>() { 1, 2, 3};

// get the object from the list
var value = list[0];
// insert it at the end of the list.
list.Insert(3, value);
// list is now { 1, 2, 3, 1} ]
相关问题