我想做的事情如下:
MyObject myObj = GetMyObj(); // Create and fill a new object
MyObject newObj = myObj.Clone();
Run Code Online (Sandbox Code Playgroud)
然后更改未在原始对象中反映的新对象.
我不经常需要这个功能,所以当有必要的时候,我已经使用了创建一个新对象然后单独复制每个属性,但它总是让我觉得有更好或更优雅的处理方式情况.
如何克隆或深度复制对象,以便可以修改克隆对象而不会在原始对象中反映任何更改?
我想要一个真正的深拷贝.在Java中,这很容易,但是你如何在C#中做到这一点?
我正在编写一个实现ICollection<T>和ICollection接口的类.
MSDN说这些有点不同.ICollection<T>.CopyTo采取T[]论证,而ICollection.CopyTo采取System.Array争论.抛出的异常之间也存在差异.
这是我对泛型方法的实现(我相信它的功能完全正常):
void ICollection<PlcParameter>.CopyTo(PlcParameter[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex");
if (array.Length - arrayIndex < Count)
throw new ArgumentException("Not enough elements after arrayIndex in the destination array.");
for (int i = 0; i < Count; ++i)
array[i + arrayIndex] = this[i];
}
Run Code Online (Sandbox Code Playgroud)
但是,该方法的非泛型版本让我感到困惑.首先,如何检查以下异常情况?
源ICollection的类型不能自动转换为目标数组的类型.
第二,有没有办法利用现有的通用实现来减少代码重复?
这是我的在制品实施:
void ICollection.CopyTo(Array array, int index) …Run Code Online (Sandbox Code Playgroud)