我假设当我们将引用类型传递给函数时,它指向同一个对象,任何更改都将反映在main方法中。但是当我初始化对新对象的引用时,行为并不像预期的那样。我知道可以使用“ref”关键字来完成,但我想知道这种行为。
class Program
{
static void Foo(StringBuilder x)
{
x = new StringBuilder(); //if this is not initialized, "helloworld" is printed i.e., same object is getting modified.
x.Append("world");
}
static void Main(string[] args)
{
StringBuilder y = new StringBuilder();
y.Append("hello");
Foo(y);
Console.WriteLine(y.ToString());//I was expecting "world" here.
Console.ReadLine();
}
}