Files

56 lines
1.1 KiB
Markdown
Raw Permalink Normal View History

2026-06-21 09:51:55 +08:00
# ref 和 out
2026-04-13 15:40:15 +08:00
通常用法:
2026-06-21 09:51:55 +08:00
- 解决“函数内部改了值,函数外部也要同步变化”的需求
- 让方法可以直接操作调用方变量
区别:
1. `ref`
- 传入前必须先初始化
- 方法内可以读,也可以写
2. `out`
- 传入前可以不初始化
- 方法返回前必须赋值
- 常用于“额外带回一个结果”
2026-04-13 15:40:15 +08:00
语法:
2026-06-21 09:51:55 +08:00
定义和调用两边都要写关键字。
`ref`
```csharp
void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
int x = 10;
int y = 20;
Swap(ref x, ref y);
Console.WriteLine($"{x}, {y}"); // 20, 10
2026-06-18 20:01:30 +08:00
```
2026-06-21 09:51:55 +08:00
`out`
```csharp
bool TryGetAge(string text, out int age)
{
return int.TryParse(text, out age);
}
if (TryGetAge("18", out int value))
{
Console.WriteLine(value);
}
2026-04-13 15:40:15 +08:00
```
注意:
2026-06-21 09:51:55 +08:00
1. ==`ref` 参数必须先初始化==
2. ==`out` 参数在方法结束前必须赋值==
3. `ref` / `out` 传的是变量本身,所以修改会影响外部
4. 对引用类型来说:
- 不加 `ref` 时,方法里可以改对象内容
-`ref` 时,连“变量指向哪个对象”都可以改
5. 属性、常量、表达式一般不能直接当 `ref` / `out` 参数传入
2026-04-13 15:40:15 +08:00
2026-06-21 09:51:55 +08:00
#基础