C#入门ref\out关键字使用

一、ref 关键字

       使用ref关键字可以将值类型变量按照引用方式进行传递;

建议:在时间开发过程当中不建议经常使用ref关键字;

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace RefOutDemo
 8 {
 9     /// <summary>
10     /// ref关键字使用
11     /// </summary>
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             //使用ref关键字可以将值类型变量按照引用方式传递;
17             int a = 10;
18             int result = Square(ref a);
19             //传递参数的时候加上ref
20             Console.WriteLine("a的平方={0} a的值={1}", result, a);
21             Console.ReadLine();
22             
23         }
24 
25         static int Square(ref int num1)//定义参数的时候加上ref
26         {
27             num1 = num1 * num1;
28             //修改参数值
29             return num1;
30         }
31     }
32 }

二、out关键字

out关键字使用:

1、out关键字其实也是使用引用方式传递,实践开发中不建议经常使用out关键字;

2、可以使用“字典集合”方式返回多个参数;

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

namespace RefOutDemo
{
    /// <summary>
    /// out关键字使用
    /// </summary>
   
        static void Main(string[] args)
        {
            int a = 10;
            int square = 0;
            int result = Operation(a, out square);
            //传递参数加上out关键字
            Console.WriteLine("a的平方={0} a的立方={1}", square, result);
            Console.ReadLine();

        }
        static int Operation(int num1,out int square) //定义参数加上out关键字
        {
            square = num1 * num1;//求平方 必须给返回值赋值
            int result = num1 * num1 * num1;//求立方
            return result;
        }

    }
}

 

posted @ 2017-07-20 15:05  sadseal  阅读(326)  评论(0编辑  收藏  举报