众所周知,String是不可变的.String不可变的原因是什么,StringBuilder类的引入是可变的?
考虑以下代码:
public class Program
{
private static void Main(string[] args)
{
var person1 = new Person { Name = "Test" };
Console.WriteLine(person1.Name);
Person person2 = person1;
person2.Name = "Shahrooz";
Console.WriteLine(person1.Name); //Output: Shahrooz
person2 = null;
Console.WriteLine(person1.Name); //Output: Shahrooz
}
}
public class Person
{
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
很显然,当分配person1到person2与Name物业person2发生变化,Name中person1也将改变.person1并person2有相同的参考.
为什么何时person2 = null,person1变量也不会为空?
我正在学习(新手).NET,我有些疑惑.
从书中读到的例子我了解到String是对象,然后是Reference Type.
所以,我做了这个测试,结果与我的预期不同:
我真的很好奇,这是一个例外,因为"字符串"是特殊类型吗?
class Program
{
static void Main(string[] args)
{
SByte a = 0;
Byte b = 0;
Int16 c = 0;
Int32 d = 0;
Int64 e = 0;
string s = "";
Exception ex = new Exception();
object[] types = { a, b, c, d, e, s, ex };
// C#
foreach (object o in types)
{
string type;
if (o.GetType().IsValueType)
type = "Value type";
else
type = "Reference Type";
Console.WriteLine("{0}: {1}", o.GetType(), type);
} …Run Code Online (Sandbox Code Playgroud)