ค่าที่ส่งคืนอ้างอิงช่วยให้เมธอดสามารถคืนค่าการอ้างอิงไปยังตัวแปร แทนที่จะเป็นค่า
จากนั้นผู้เรียกสามารถเลือกที่จะปฏิบัติต่อตัวแปรที่ส่งคืนราวกับว่ามันถูกส่งคืนโดยค่าหรือโดยการอ้างอิง
ผู้เรียกสามารถสร้างตัวแปรใหม่ซึ่งเป็นตัวอ้างอิงถึงค่าที่ส่งคืน ซึ่งเรียกว่า ref local
ในตัวอย่างด้านล่าง แม้ว่าเราจะปรับเปลี่ยนสี แต่ก็ไม่มีผลกระทบใดๆ กับสีอาร์เรย์ดั้งเดิม
ตัวอย่าง
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
เพื่อให้บรรลุเป้าหมายนี้ เราสามารถใช้ประโยชน์จากผู้อ้างอิงได้
ตัวอย่าง
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