Files
2026-06-21 09:51:55 +08:00

56 lines
1.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ref 和 out
通常用法:
- 解决“函数内部改了值,函数外部也要同步变化”的需求
- 让方法可以直接操作调用方变量
区别:
1. `ref`
- 传入前必须先初始化
- 方法内可以读,也可以写
2. `out`
- 传入前可以不初始化
- 方法返回前必须赋值
- 常用于“额外带回一个结果”
语法:
定义和调用两边都要写关键字。
`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
```
`out`
```csharp
bool TryGetAge(string text, out int age)
{
return int.TryParse(text, out age);
}
if (TryGetAge("18", out int value))
{
Console.WriteLine(value);
}
```
注意:
1. ==`ref` 参数必须先初始化==
2. ==`out` 参数在方法结束前必须赋值==
3. `ref` / `out` 传的是变量本身,所以修改会影响外部
4. 对引用类型来说:
- 不加 `ref` 时,方法里可以改对象内容
-`ref` 时,连“变量指向哪个对象”都可以改
5. 属性、常量、表达式一般不能直接当 `ref` / `out` 参数传入
#基础