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;
        }
    }
}
相关文章
相关标签/搜索