我正在尝试以下代码:
public class cloneTest : ICloneable {
public string strValue { get; set; }
public object Clone( ) {
cloneTest n = new cloneTest( );
n.strValue = this.strValue;
return n;
}
}
cloneTest obj1 = new cloneTest( ) { strValue = "one" };
cloneTest obj2 = new cloneTest( ) { strValue = "two" };
cloneTest obj3 = new cloneTest( ) { strValue = "three" };
cloneTest[ ] strValueArray = new cloneTest[ ] {obj1, obj2, obj3};
cloneTest[ ] strValueArrayClone = ( cloneTest[ ] )strValueArray.Clone( );
strValueArrayClone[ 2 ].strValue = "four";
当我按照代码中的指定修改 strValuArrayClone 对象时,即使我正在创建克隆,此更改也会反映在 strValueArray 对象中。但是,如果尝试下面的代码,那么一切都会顺利进行。我想了解它背后的逻辑。
cloneTest obj1 = new cloneTest( ) { strValue = "one" };
cloneTest obj2 = new cloneTest( ) { strValue = "two" };
cloneTest obj3 = new cloneTest( ) { strValue = "three" };
cloneTest[ ] strValueArray = new cloneTest[ ] {obj1, obj2, obj3};
cloneTest[ ] strValueArrayClone = ( cloneTest[ ] )strValueArray.Clone( );
cloneTest obj2clone = ( cloneTest )obj2.Clone( );
obj2clone.strValue = "six";
strValueArrayClone[ 2 ] = obj2clone;