C#基礎增強(7)之ref與out

介紹

給方法傳遞普通參數時,值類型傳遞的是拷貝的對象,而引用類型傳遞的是對象的引用。它們都不能在函數內部直接修改外部變量的引用(不是修改引用類型的屬性),而使用 ref 或 out 關鍵字就能夠實現。函數

做用

ref:在方法內部修改外部變量的引用。spa

out:方法內部給外部變量初始化,至關於一個函數多個返回值。code

注意事項:對象

  1. 使用 ref 修飾參數時,傳入的參數必須先被初始化,方法中能夠不復制。而對 out 而言,必須在方法中對其完成初始化,在方法外部不用初始化。
  2. 使用 ref 和 out 時,在執行方法時,參數前都須要加上 ref 或 out 關鍵字。
  3. out 適合用在須要 return 多個返回值的地方,而 ref 則用在須要被調用的方法修改調用者的引用時。

示例

例 1:交換兩個變量的值:blog

internal class Program
{
    public static void Main(string[] args)
    {
        int i = 3;
        int j = 4;
        Swap(ref i,ref j);
        Console.WriteLine(i); // 4
        Console.WriteLine(j); // 3
    }

    public static void Swap<T>(ref T obj1, ref T obj2)
    {
        object temp = obj1;
        obj1 = obj2;
        obj2 = (T) temp;
    }
}

例 2:本身實現 int.TryParse() 方法:ip

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); // -1
        Console.WriteLine(result2); // 342
    }

    /**
     * 將字符串轉換成一個 int 類型,以 out 參數 result 返回,若是出現異常,result 值爲 -1
     */
    public static void TryParse(string numStr, out int result)
    {
        try
        {
            var num = Convert.ToInt32(numStr);
            result = num;
        }
        catch (Exception e)
        {
            result = -1;
        }
    }
}
相關文章
相關標籤/搜索