1.ref:ref 即refence,又叫引用,类似于c++中的&,会将值和变量一起传入方法
2.out:主要用于函数返回多个值,在有out参数方法内,相应的值必须初始化,不然无法通过编译
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program {
static void Main(string[] args) {
int a = 40, b = 5;
OutFun(out a, out b);
Console.WriteLine("OutFun : a = {0} , b = {1}", a, b);//OutFun : a = 3 , b = 1
int c = 10, d = 3; RefFun(ref c, ref d);
Console.WriteLine("RefFun : c = {0} , d = {1}", c, d);//RefFun : c = 13 , d = 1
int e = 3, f = 4;
NorFun(e, f);
Console.WriteLine("RefFun : c = {0} , d = {1}", e, f);//NorFun : c = 3 , d = 4
Console.ReadLine(); }
private static void NorFun(int a, int b){a = a + b; b = 1;}
static void OutFun(out int a, out int b) { a = 1; b = 2; a = a + b; b = 1; }
static void RefFun(ref int a, ref int b) { a = a + b; b = 1; } }
}
输出结果的原因:
Outfun返回的是在函数里定义的值
RefFun会把变量的地址传到方法里,在方法里修改会直接改变原本变量的值
NorFun是普通调用,方法里修改值不会改变原本的值
不过这个感觉并没有什么对比性,因为out和ref虽然在编译的时候编译器会把之归为一种类型,但是out更主要的用法应该是在方法内部对变量进行初始化/改变,然后传到调用方法一端,达成一种反向传值(当然只是我个人的见解)