根据我在C#中的理解,当一个对象被分配给另一个相同类型的对象时,它的引用被复制而不是值。所以我想知道如何将一个对象分配给另一个对象,使其值被复制而不被引用到第二个对象。
答案 0 :(得分:5)
您可以看到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";
}
答案 1 :(得分:-1)
您必须克隆对象而不是分配引用。