1.概要
ref 和out 到底有什么差别,从使用的角度其实差别不大。唯一不同的是,out在函数内初始化,而ref必须在函数外部初始化。Out的功能更想是真正的返回值。而ref更像是引用的变量。1.
2.代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ref和Out的差别
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("ref和Out的差别");
Program program = new Program();
program.main();
Console.ReadKey();
}
private void main() {
Ref @ref = new Ref();
@ref.test();
Out @out = new Out();
@out.test();
}
class Ref {
public void test()
{
//int a;//err 使用了为赋值的局部变量
int a = 0;
testRef(ref a);
Console.WriteLine("值:" + a);
}
private void testRef(ref int a)
{
a = 5;
}
}
class Out {
public void test()
{
int a;
testOut(out a);
Console.WriteLine("值:" + a);
}
private void testOut(out int a)
{
a = 5;
}
}
}
}