参数传递关键字 ref 与 out
前置文章
C#系列之ref和out的区别_c# ref 和out区别-CSDN博客
如何使用
在C#中,ref
和out
都是用于向方法传递参数的关键字,但它们有一些不同之处:
- ref关键字:
ref
关键字用于将变量传递给方法,并允许方法修改该变量的值。- 传递给
ref
参数的变量必须在调用方法之前被初始化。 - 在方法内部对
ref
参数的修改会影响到调用者原始变量的值。
示例 :
void ModifyWithRef(ref int x)
{
x = 10; // 修改x的值
}
int value = 5;
ModifyWithRef(ref value);
Console.WriteLine(value); // 输出 10
- out关键字:
out
关键字与ref
类似,也用于将变量传递给方法,但out
参数无需在调用方法之前初始化。- 在方法内部,必须确保为
out
参数赋值,否则编译器会报错。 - 与
ref
不同,out
参数无需在调用方法之前初始化,因为在方法内部,它们会被初始化。
示例:
void InitializeWithOut(out int x)
{
x = 10; // 初始化x的值
}
int value;
InitializeWithOut(out value);
Console.WriteLine(value); // 输出 10
因此,主要区别在于ref
参数在传递给方法之前必须初始化,而out
参数则不需要。
实例
using System;
class test
{
public static void swap1(ref string a, ref string b)
{
string t = a;
a = b;
b = t;
}
public static void swap2(out string a, out string b)
{
// 必须重新赋值
a = "123";
b = "456";
string t = a;
a = b;
b = t;
}
public static void Main(string[] args)
{
string a = "abc";
string b = "def";
Console.WriteLine(a);
Console.WriteLine(b);
swap1(ref a, ref b);
Console.WriteLine(a);
Console.WriteLine(b);
swap2(out a, out b);
Console.WriteLine(a);
Console.WriteLine(b);
}
}
输出 :
abc
def
def
abc
456
123