I know that string is a reference type, but I'm having problem understanding why string outside the "refTest" class or function won't behave like the one inside the class "refTest". I mean if I have 2 string named "name" and "name2", and both have the same value since name2 has a copy of name, it will output the same value "A", but then I change the second string value to "B" and this time name and name2 have different value "A" and "B", and then when I do the same thing with a string that is from a class "refTest" it will output name1 and name2 the same value. Aren't both string reference type? Which means they have a pointer on a heap. Right?
I'm getting confused on why string outside the class "refTest" will output a different outcome compared to the one inside the "refTest" class.
Or it is that everytime I declare a string outside the "refTest" class, it will be stored on a different address (heap address)?
class Program
{
static void Main(string[] args)
{
string name = "A";
string name2 = name;
Console.WriteLine(name2 + " " + name);
// >> A A
name2 = "B";
Console.WriteLine(name2 + " " + name);
// >> A B
refTest test = new refTest();
test.rTName = "A";
Console.WriteLine(test.rName);
// >> A
refTest test2 = test;
test2.rName = "B";
Console.WriteLine($"test.rName = {test.rName}, test2.rName = {test2.rName}");
// >> test.rName = B, test2.rName = B
Console.ReadLine();
}
}
class refTest
{
public string rName;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…