C#基础加强(7)之ref与out
生活随笔
收集整理的這篇文章主要介紹了
C#基础加强(7)之ref与out
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
介紹
給方法傳遞普通參數(shù)時,值類型傳遞的是拷貝的對象,而引用類型傳遞的是對象的引用。它們都不能在函數(shù)內(nèi)部直接修改外部變量的引用(不是修改引用類型的屬性),而使用 ref 或 out 關(guān)鍵字就可以實現(xiàn)。
作用
ref:在方法內(nèi)部修改外部變量的引用。
out:方法內(nèi)部給外部變量初始化,相當(dāng)于一個函數(shù)多個返回值。
注意事項:
示例
例 1:交換兩個變量的值:
internal class Program {public static void Main(string[] args){int i = 3;int j = 4;Swap(ref i,ref j);Console.WriteLine(i); // 4Console.WriteLine(j); // 3 }public static void Swap<T>(ref T obj1, ref T obj2){object temp = obj1;obj1 = obj2;obj2 = (T) temp;} }例 2:自己實現(xiàn)?int.TryParse()?方法:
internal class Program {public static void Main(string[] args){string numStr1 = "abc";string numStr2 = "342";int result1;int result2;TryParse(numStr1, out result1);TryParse(numStr2, out result2);Console.WriteLine(result1); // -1Console.WriteLine(result2); // 342 }/*** 將字符串轉(zhuǎn)換成一個 int 類型,以 out 參數(shù) result 返回,如果出現(xiàn)異常,result 值為 -1*/public static void TryParse(string numStr, out int result){try{var num = Convert.ToInt32(numStr);result = num;}catch (Exception e){result = -1;}} }轉(zhuǎn)載于:https://www.cnblogs.com/zze46/p/10706397.html
總結(jié)
以上是生活随笔為你收集整理的C#基础加强(7)之ref与out的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。