Pet*_*etr 2 c# string reference object
当我有这个代码时:
class A
{
public int X = 0;
...
}
public void Function()
{
// here I create a new instance of class
A a = new A();
a.X = 10;
// here I create a pointer to null
A b = null;
// here I assign a to b
b = a;
b.X = 20;
}
Run Code Online (Sandbox Code Playgroud)
我现在将引用传递给了A类的实例吗?或者我将A的实例克隆到新实例并在b中创建了对它的引用?
在b中改变X也在改变X中的X?为什么?如果没有,创建a的副本并将其插入b的正确方法是什么?
为什么与字符串相同会始终创建副本?是否在字符串中覆盖了相等的运算符?
string a = "hello";
string b = a;
b = "world";
// "hello world"
Console.WriteLine( a + " " + b );
Run Code Online (Sandbox Code Playgroud)
C#使用引用而不是指针.课程是reference types.
在您的示例中, b具有相同的引用a.它们引用内存上的相同位置.
改变b中的X也改变了?为什么?
是的,因为它们引用相同的对象并且更改一个引用将影响另一个引用.
string a = "hello";
string b = a;
b = "world";
// "hello world"
Console.WriteLine( a + " " + b );
Run Code Online (Sandbox Code Playgroud)
字符串也是引用类型.但他们也是immutable type.这意味着你无法改变它们.即使你认为你改变它们,你实际上创建了新的字符串对象.
"hello"一个名为的引用a.b引用同一对象的新引用.("hello")b引用新对象的行"world".您的参与"hello"不再是引用对象了.| 归档时间: |
|
| 查看次数: |
2277 次 |
| 最近记录: |