Files
My-Notes/笔记/CSharp/基础/ref和out.md
T
2026-06-18 20:01:30 +08:00

48 lines
1.1 KiB
Markdown
Raw 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的区别:==
ref
- 传入的参数必须初始化(赋值)
- 方法内可读可写
out
- 传入前**可以不初始化**
- 方法内**必须赋值**,否则编译报错
语法:
在函数传参时,两边都要加上修饰词
ref
```Csharp
//交换数字
void Swap(ref int a, ref int b)
{
int temp = a; a = b; b = temp;
}
```
out:
```Csharp
//最经典:int.TryParse
if (int.TryParse(Console.ReadLine(), out int value))
Console.WriteLine(value % 2 == 0 ? "even" : "odd");
//int.TryParse伪代码
//bool ReadConfig(string key, out string value)
//{
// if (配置存在)
// {
// value = 读取到的值; return true;
// }
// else
// {
// value = null; return false;
// }
//}
```
案例:
原型在[[值类型和引用类型]]笔记中
注意:
==out不是用来让内外值一定不等==
==ref传入的参数必须初始化==
如果传入引用类型且内外不同,推荐new一个
#基础