当您通过引用传递值类型时: A) 如果该方法分配参数来引用不同的对象,则调用者看不到这些更改。
public int Sq(ref int number)
{
// Assigned a different instance means it address is different from what is passed
number = new int();
number = 10;
return number;
}
但是这里的更改在调用中可见
B) 如果该方法修改了参数引用的对象的状态,则这些更改对调用者是可见的。
public int Sq(ref int number)
{
//Modifying number to 10 and this cannot visible in called method
number = 10;
return number;
}
我理解了B,但是如何证明A。请帮我提供正确的代码来证明A
这绝对不是真的 - 我尝试了几个例子,即使我重新分配 new() ,调用函数中仍然会发生更改。 例如:
public static string Sq(ref string str)
{
str = new string("blabla");
return str;
}
public static string Sq2(ref string str)
{
str = "blabla";
return str;
}
static void Main(string[] args)
{
string sq="hi", sq2="hi";
Console.WriteLine("sq="+sq+" sq2="+sq2);//output: sq=hi sq2=hi
Sq(ref sq);
Sq2(ref sq2);
Console.WriteLine("sq="+ sq+ " sq2="+ sq2);//output: sq=blabla sq2=blabla
}
变量
sq
已更改,即使它已在函数中分配了新位置。 (这个例子是可以运行的)