c#——ref&out

引用参数 ref
ref的作用,有点类似于c中的指针,即可以修改实参的值,在使用ref时,需注意如下:ref修饰的参数一定是变量,并且要提前赋值。

            Console.WriteLine("{0},{1}", b.js1(ref 1),a);

上述代码中,ref修饰的是常量,会显示如下错误
这里写图片描述

        static void Main(string[] args)
        {
            int a;
            Program b = new Program();
            Console.WriteLine("{0},{1}", b.js1(ref a));
        }

上述代码中,变量a在使用前没赋值,会显示如下错误
这里写图片描述

输入参数 out
类似于ref关键字,但是out修饰的变量可以不事先赋值,而是在方法内部赋值。

下面这段代码区分了普通形参,ref和out修饰的参数的区别

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ref_and_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            a = 1;
            Program b = new Program();
            Console.WriteLine("{0},{1}", b.js(a),a);
            Console.WriteLine("{0},{1}", b.js1(ref a),a);
            Console.WriteLine("{0},{1}", b.js2(out a), a);
            Console.ReadLine();
        }
        public int js(int a)
        {
            a += a;
            return a;
        }
        public int js1(ref int a)
        {
            a += a;
            return a;
        }
        public int js2(out int a)
        {
            a = 2;
            a += a;
            return a;
        }
    }
}

输出结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/WindSymphony/article/details/82154348
今日推荐