引用參數用於引用變數的記憶體位置。與需要新儲存位置的值參數不同,引用參數表示與作為參數傳遞給方法的原始參數相同的記憶體位置。在C#中,我們使用關鍵字“ref”來聲明引用參數。當我們將引用參數作為參數傳遞給 C# 中的函數時,我們傳遞的是對記憶體位置的引用而不是原始值。我們在 C# 中將此概念稱為「按引用呼叫」。
文法
ref data_typevariable_name
其中 data_type 是變數名稱為變數的資料型態。
下面給出了提到的範例:
示範按引用呼叫的 C# 程序,其中我們計算數字的平方並在按引用呼叫函數之前和呼叫函數之後顯示值。
代碼:
using System; //a namespace called program1 is defined namespace program1 { //a class called check is defined class check { //a function is defined which takes reference variable as an argument public void displaypower(ref double value) { //the square of the passed value is found using pow method double power = Math.Pow(value,2); //The resulting value is added to the value passed as reference value = value + power; Console.WriteLine("Value when the control is inside the function "+value); } //main method is called static void Main(string[] args) { //a double variable is defined double value = 5; //an instance of the check class is defined which consists of the function taking reference parameter as an argument check check1 = new check(); Console.WriteLine("Value before the function is called "+value); //a function is called by reference check1.displaypower(ref value); Console.WriteLine("The value of the variable remains the same as inside the function because we are calling the function by reference " + value); } } }
輸出:
說明:
示範按引用呼叫的 C# 程序,其中我們透過引用呼叫函數並將小寫字母字串作為引用參數傳遞,將給定的小寫字母字串轉換為大寫字母。
代碼:
using System; //a namespace called program1 is defined namespace program1 { //a class called check is defined class check { //a function is defined which takes reference variable as an argument public void displayupper(ref string value) { //ToUpper method is used to convert the string from small letters to capital letters value = value.ToUpper(); Console.WriteLine("Value when the control is inside the function "+value); } //main method is called static void Main(string[] args) { //a double variable is defined string value = "shobha"; //an instance of the check class is defined which consists of the function taking reference parameter as an argument check check1 = new check(); Console.WriteLine("Value before the function is called "+value); //a function is called by reference check1.displayupper(ref value); Console.WriteLine("The value of the variable remains the same as inside the function because we are calling the function by reference " + value); } } }
輸出:
說明:
推薦文章
這是 C# Call By Reference 的指南。在這裡,我們透過工作和程式設計範例來討論介紹。您也可以查看以下文章以了解更多資訊 –
以上是C# 透過引用調用的詳細內容。更多資訊請關注PHP中文網其他相關文章!