在C#7.0中,什么是Ref当地人和Ref返回?
引用返回值允许方法返回对变量而不是值的引用。
然后,调用者可以选择将返回的变量视为按值或引用返回。
调用者可以创建一个新变量,该变量本身就是对返回值的引用,称为reflocal。
在下面的示例中,即使我们修改了颜色,它对原始数组的颜色也没有任何影响
示例
class Program{
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
string color = colors[3];
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}
}输出结果
blue green yellow orange pink
为此,我们可以使用reflocals
示例
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
ref string color = ref colors[3];
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}输出结果
blue green yellow Magenta pink
引用返回-
在下面的示例中,即使我们修改了颜色,它对原始数组的颜色也没有任何影响
示例
class Program{
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
string color = GetColor(colors, 3);
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}
public static string GetColor(string[] col, int index){
return col[index];
}
}输出结果
蓝绿色黄色橙色粉红色
示例
class Program{
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
ref string color = ref GetColor(colors, 3);
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}
public static ref string GetColor(string[] col, int index){
return ref col[index];
}
}输出结果
blue green yellow Magenta pink