พารามิเตอร์อ้างอิง
พารามิเตอร์อ้างอิงคือการอ้างอิงถึงตำแหน่งหน่วยความจำของตัวแปร เมื่อคุณส่งผ่านพารามิเตอร์โดยการอ้างอิง ซึ่งแตกต่างจากพารามิเตอร์ของค่า ตำแหน่งการจัดเก็บใหม่จะไม่ถูกสร้างขึ้นสำหรับพารามิเตอร์เหล่านี้
คุณสามารถประกาศพารามิเตอร์อ้างอิงได้โดยใช้คีย์เวิร์ด ref ต่อไปนี้เป็นตัวอย่าง −
ตัวอย่าง
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void swap(ref int x, ref int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
int b = 200;
Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);
/* calling a function to swap the values */
n.swap(ref a, ref b);
Console.WriteLine("After swap, value of a : {0}", a);
Console.WriteLine("After swap, value of b : {0}", b);
Console.ReadLine();
}
}
} ผลลัพธ์
Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100
พารามิเตอร์ขาออก
คำสั่ง return สามารถใช้สำหรับการคืนค่าเพียงหนึ่งค่าจากฟังก์ชัน อย่างไรก็ตาม เมื่อใช้พารามิเตอร์ out คุณสามารถคืนค่าสองค่าจากฟังก์ชันได้
ต่อไปนี้เป็นตัวอย่าง −
ตัวอย่าง
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValue(out int x ) {
int temp = 10;
x = temp;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 150;
Console.WriteLine("Before method call, value of a : {0}", a);
/* calling a function to get the value */
n.getValue(out a);
Console.WriteLine("After method call, value of a : {0}", a);
Console.ReadLine();
}
}
} ผลลัพธ์
Before method call, value of a : 150 After method call, value of a : 10