根据我在C#中的理解,当一个对象被分配给另一个相同类型的对象时,它的引用被复制而不是值.所以我想知道如何将一个对象分配给另一个对象,使其值被复制而不被引用到第二个对象.
您可以看到test2.ErrorDetail更改为"DTL2",而test1.ErrorDetail仍为"DTL1".
public class TestClone : ICloneable
{
public bool IsSuccess { get; set; }
public string ErrorCode { get; set; }
public string ErrorDetail { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
static void Main(string[] args)
{
var test1 = new TestClone() { IsSuccess = true, ErrorCode = "0", ErrorDetail = "DTL1" };
var test2 = (TestClone) test1.Clone();
test2.ErrorDetail = "DTL2";
}
Run Code Online (Sandbox Code Playgroud)