C# ref,out

static void Main(string[] args)
{
int a = 1;
int b = 2;
string x = "x";
string y = "y";

Console.WriteLine("Main-->a:{0},b:{1}", a, b);
Console.WriteLine("Main-->x:{0},y:{1}", x, y);

TestInt(a, b);
TestString(x, y);

Console.WriteLine("Main-->a:{0},b:{1}", a, b);
Console.WriteLine("Main-->x:{0},y:{1}", x, y);

TestIntRef(ref a, ref b);
TestStringRef(ref x, ref y);

Console.WriteLine("Main-->a:{0},b:{1}", a, b);
Console.WriteLine("Main-->x:{0},y:{1}", x, y);
}

public static void TestInt(int a, int b)
{
a = 10;
b = 20;
Console.WriteLine("TestInt-->a:{0},b:{1}", a, b);
}

public static void TestIntRef(ref int a, ref int b)
{
a = 100;
b = 200;
Console.WriteLine("TestIntRef-->a:{0},b:{1}", a, b);
}

public static void TestString(string x, string y)
{
x = "123x";
y = "123y";
Console.WriteLine("TestString-->x:{0},y:{1}", x, y);
}

public static void TestStringRef(ref string x, ref string y)
{
x = "ref:123x";
y = "ref:123y";
Console.WriteLine("TestStringRef-->x:{0},y:{1}", x, y);
}
 

Out:

static void Main(string[] args)
{
int a;
string x, y;
TestOut(out a);
Console.WriteLine(a);  //a等于101s
}

public static void TestOut(out int a)
{
a = 101;
}

总结:out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字

原文地址:https://www.cnblogs.com/kelei12399/p/2316389.html