我不认为 DataGridViewColumnHeaderCell 实现了 IClonable 所以我正在考虑使用 Xml.Serialization 来复制这个对象以避免不必要的引用。你怎么看?矫枉过正?
2 回答
You haven't to do it, DataGridViewColumnHeaderCell
implements the IClonable.Clone()
method.
object clonedObject = myDataGridViewColumnHeaderCell.Clone();
EDIT:
but it doesn't copy the data. And ColumnIndex is a readonly property which is one of 2 properties I'm interested in preserving.
Sincerly I've never used it on DataGridViewColumnHeaderCell
, but it should work.
Howerever If you just need to preserve two properties you can create your customized Clone method:
public static class Utilities{
public static object CloneObject(this DataGridViewColumnHeaderCell myObj){
DataGridViewColumnHeaderCell clonedObject = new DataGridViewColumnHeaderCell();
//here clone your properties
clonedObject.ColumnIndex = myObj.ColumnIndex;
return clonedObject;
}
}
Then:
object clonedObject = myDataGridViewColumnHeaderCell.CloneObject();
PS: In the case of ColumnIndex
you just need to assign it to the new object because it's of type int which is a struct and you don't pass a reference.
我对此进行了测试,克隆从未出于某种未知原因复制该对象。我不得不复制每一行的属性。