引用类型中的引用类型对象和字符串 [英] refrence types object and string in same reference

查看:85
本文介绍了引用类型中的引用类型对象和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果对象和字符串是引用类型,为什么在此代码中,当p分配"sample"时,q不引用p并且其值为null?

if object and string is refrence type,why in this code when p assigned with "sample" ,q not refrence to p and its value is null ?

string p = null;
       string q = p;
       p = "sample";    //p value is sample,q value is null

推荐答案

上面的示例中发生的事情是p现在指向一个新的字符串对象.
q仍然指向旧字符串,该字符串为null.

通常,字符串是引用类型,但是它们的行为略有不同.
尽管字符串是引用类型,但它们是不可变的.

因此,字符串对象的内容在创建对象后就无法更改,尽管语法使它看起来好像可以执行此操作.

此处 [
What is happening in your example above is that p is now pointing to a new string object.
q still points to the old string, the string which was null.

In general, strings are reference types, but they behave slightly differently.
Although strings are reference type, they are immutable.

So the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.

Read more about this here[^].


因为"q"和"p"是两个参考变量:
Because "q" and "p" are both reference variables:
string p = null;


声明一个名为p的变量,为其分配值null


Declares a variable called p, assigns it the value null

string q = p;


声明一个单独的变量q,为它分配当前在p中的值-即null


Declares a separate variable called q, assignes it the value currently in p - i.e. null

p = "sample";


分配p指向包含样本"的字符串.
这不会改变q-保留先前的null

有点像汽车.如果您有"p"和"q"两辆车,然后开车"p"去商店,您是否希望"q"独自跟随您去那里?


Assigns p to refer to a string which contains "sample".
This does not alter q - it remains with the previous value of null

It''s a bit like cars. If you have two cars, "p" and "q" and you drive "p" to the shops, would you expect "q" to follow you there on it''s own?


由于字符串是一个不变的 object 参考变量,因此您实际上并没有更改现有对象的值,而是用新的字符串替换了先前的字符串.

请参考:
字符串(C#参考) [
Since string is an immutable object reference variable you''re not actually changing the value of an existing object but replacing the previous string with a new one.

Refer to: string (C# Reference)[^]


这篇关于引用类型中的引用类型对象和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆