C# ref与out关键字解析
簡介:ref和out是C#開發中經常使用的關鍵字,所以作為一個.NET開發,必須知道如何使用這兩個關鍵字.
1、相同點
ref和out都是按地址傳遞,使用后都將改變原來參數的數值。
?
2、ref關鍵字
(1)、使用ref關鍵字的注意點:
i、方法定義和調用方法都必須顯式使用?ref?關鍵字
ii、傳遞到?ref?參數的參數必須初始化,否則程序會報錯
iii、通過ref的這個特性,一定程度上解決了C#中的函數只能有一個返回值的問題
?
(2)、代碼示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApplication1 {class Program{static void Main(string[] args){int a = 6;int b = 66;Fun(ref a,ref b);Console.WriteLine("a:{0},b:{1}", a, b);//輸出:72和6說明傳入Fun方法是a和b的引用 }static void Fun(ref int a, ref int b) {a = a+b; //72,說明Main方法的a和b的值傳進來了b = 6;}} }?
?
(2)、out關鍵字
(1)、使用out關鍵字的注意點:
i、方法定義和調用方法都必須顯式使用?out關鍵字
ii、out關鍵字無法將參數值傳遞到out參數所在的方法中,只能傳遞參數的引用(個人理解),所以out參數的參數值初始化必須在其方法內進行,否則程序會報錯
iii、通過out的這個特性,一定程度上解決了C#中的函數只能有一個返回值的問題
?
(2)、代碼示例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApplication1 {class Program{static void Main(string[] args){int a=100;int b;Fun(out a, out b);Console.WriteLine("a:{0},b:{1}", a, b);//輸出:3和1說明out參數傳遞進去的是a和b的引用,輸出3說明a的參數值沒有傳入Fun方法中 }static void Fun(out int a, out int b){a = 1+2;b = 1;}} }?
(3)、ref和out的區別
通過上面的解析,ref和out最主要的區別是:
ref將參數的參數值和引用都傳入方法中,所以ref的參數的初始化必須在方法外部,進行,也就是ref的參數必須有初始化值,否則程序會報錯
out不會將參數的參數值傳入方法中,只會將參數的引用傳入方法中,所以參數的初始化工作必須在其對用方法中進行,否則程序會報錯
?
(4)、ref和out的使用需注意
i、
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApplication1 {class Program{public void SampleMethod(ref int i) { }public void SampleMethod(out int i) { }} }盡管?ref?和?out?在運行時的處理方式不同,但在編譯時的處理方式相同。因此,如果一個方法采用?ref?參數,而另一個方法采用?out?參數,則無法重載這兩個方法。例如,從編譯的角度來看,以下代碼中的兩個方法是完全相同的,因此將不會編譯上面的代碼
ii、
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApplication1 {class Program{public void SampleMethod(int i) { }public void SampleMethod(ref int i) { }} }但是,如果一個方法采用?ref?或?out?參數,而另一個方法不采用這兩個參數,則可以進行重載
?
轉載于:https://www.cnblogs.com/GreenLeaves/p/6843026.html
總結
以上是生活随笔為你收集整理的C# ref与out关键字解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解Joomla!模板
- 下一篇: C#编程(三十五)----------f