c#中的ref和out

ref和out关键字都是用来按地址传递的,使用后都将改变原来参数的数值。

ref

传递到 ref 参数的参数必须最先初始化。这与 out 不同,后者的参数在传递之前不需要显式初始化。

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        int result = calc.Add(ref a, ref b);
        Console.WriteLine(result);
        Console.ReadKey();
    }

    public class calc
    {
        public static int Add(ref int a,ref int b)
        {
            return a+b;
        }
    }
}

out

out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。

class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;
            int result = calc.Add(ref a, ref b);
            Console.WriteLine(result);
            Console.ReadKey();
        }

        public class calc
        {
            public static int Add(out int a, out int b)
            {
                a = 10;
                b = 20;
                return a + b;
            }
        }
    }

注意

尽管 ref 和 out 在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法
下面的代码会报错:无法定义重载方法”Add”,因为它与其他方法仅在ref和out上有差别

static void Main(string[] args)
        {
            int a = 10;
            int b = 20;
            int result = calc.Add(ref a, ref b);
            result = calc.Add(out a, out b);//报错
            Console.WriteLine(result);
            Console.ReadKey();
        }
public class calc
{
    public static int Add(out int a, out int b)
        {
            a = 10;
            b = 20;
            return a + b;
        }
    public static int Add(ref int a,ref int b)
        {
            return a+b;
        }
}

但是,但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:

public class calc
{
    public static int Add(int a,int b)
    public static int Add(ref int a,ref int b)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章