意外对象引用
Accidental Object Reference
我在做我的一个项目时,有些事情没有按我的预期进行,现在我正在重新评估我的整个人。采取以下class和方法:
public class Test{
public string Name { get; set; }
public int Value { get; set; }
}
public Test ReturnExample(Test test)
{
Test example = test;
example.Name = "abc";
return example;
}
现在,如果我有一个 FirstValue
和一个 SecondValue
:
Test FirstValue = new Test {Name = "First", Value = 8 };
Test SecondValue = new Test {Name = "Second", Value = 12 };
到目前为止,一切看起来都非常普通和简单,但令我惊讶的是当你这样做时:
SecondValue = ReturnExample(FirstValue);
我期望的值是:
FirstValue:
Name = "First"
Value = 8
SecondValue:
Name = "abc"
Value = 8
然而,我得到的是:
FirstValue:
Name = "abc"
Value = 8
SecondValue:
Name = "abc"
Value = 8
那么,这里发生了什么,我可以改变什么来获得我想要的东西?
基于this:
Reference Types are used by a reference which holds a reference
(address) to the object but not the object itself. Because reference
types represent the address of the variable rather than the data
itself, assigning a reference variable to another doesn't copy the
data. Instead it creates a second copy of the reference, which refers
to the same location of the heap as the original value. Reference Type
variables are stored in a different area of memory called the heap.
This means that when a reference type variable is no longer used, it
can be marked for garbage collection.
话虽如此,如果您希望代码按预期工作,则需要进行深度复制:
public Test ReturnExample(Test test)
{
Test example = new Test();
example.Name = "abc";
example.Value = test.Value;
return example;
}
我在做我的一个项目时,有些事情没有按我的预期进行,现在我正在重新评估我的整个人。采取以下class和方法:
public class Test{
public string Name { get; set; }
public int Value { get; set; }
}
public Test ReturnExample(Test test)
{
Test example = test;
example.Name = "abc";
return example;
}
现在,如果我有一个 FirstValue
和一个 SecondValue
:
Test FirstValue = new Test {Name = "First", Value = 8 };
Test SecondValue = new Test {Name = "Second", Value = 12 };
到目前为止,一切看起来都非常普通和简单,但令我惊讶的是当你这样做时:
SecondValue = ReturnExample(FirstValue);
我期望的值是:
FirstValue:
Name = "First"
Value = 8
SecondValue:
Name = "abc"
Value = 8
然而,我得到的是:
FirstValue:
Name = "abc"
Value = 8
SecondValue:
Name = "abc"
Value = 8
那么,这里发生了什么,我可以改变什么来获得我想要的东西?
基于this:
Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value. Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection.
话虽如此,如果您希望代码按预期工作,则需要进行深度复制:
public Test ReturnExample(Test test)
{
Test example = new Test();
example.Name = "abc";
example.Value = test.Value;
return example;
}