C#简单的分析 ref 与out的使用

来源:互联网 发布:mac迅雷会员无法加速 编辑:程序博客网 时间:2024/05/19 09:01

首先在项目中的使用,注意事项。

主要是ref 能够把参数原本值带进函数内,经过一些运算,然后再带出去。(注意参数的值必须在调用之前赋值)

out是先把参数没有进行赋值,带进函数内,首先要经过赋值,接着经过一些运算,然后在带出去。(注意参数的值必须在内部先进行赋值,再操作)

简单的叙述,ref有进有出,out只出不进。

下面是一个简单的举例:

  static void Main(string[] args)
        {
            int f = 10 ;
           ExampleOut(out f);
           Console.WriteLine(f);//此时输出f值为8
           ExampleRef(ref f);
           Console.WriteLine(f);//此时输出f值为9
           Console.ReadLine();
           
          
        }
        public static void ExampleOut(out int  i)
        {

            i=8;//如果不赋值的话,则会报错。
        }
        public static void ExampleRef(ref int i) {
            i++;
        }

再接着写一点,关于类的内部函数重载的注意事项
如果仅是以out,ref做为函数重载的条件化,则会报错。(错误信息:错误 1 无法定义重载方法“Example”,因为它与其他方法仅在 ref 和 out 上有差别)
如下面的例子:
 static void Main(string[] args)
        {
            int f ;
           Example(out f);
           Console.WriteLine(f);
         
           Example(ref f);
           Console.WriteLine(f);
           Console.ReadLine();
           
        }
        public static void Example(out int  i)
        {
            i=8;
        }
        public static void Example(ref int i) {
            i++;
        }

请看下面正确的例子。如果一个方法采用 ref out参数,而另一个方法不采用这两个参数,则可以进行重载
  static void Main(string[] args)
        {
            int f =1;
           Example( f);
           Console.WriteLine(f);
         
           Example(ref f);
           Console.WriteLine(f);
           Console.ReadLine();
           
        }
        public static void Example(int  i)
        {
            i=8;
        }
        public static void Example(ref int i) {
            i++;
        }

0 0
原创粉丝点击