home commit with new plugins

This commit is contained in:
2026-06-21 09:51:55 +08:00
parent ebb9e385c5
commit 3d067fe75c
85 changed files with 10794 additions and 1443 deletions
+47 -40
View File
@@ -1,48 +1,55 @@
# ref 和 out
通常用法:
解决值[[值类型和引用类型]]在函数外部互相传递时的问题
函数内部改外部传入也改
==ref和out的区别:==
ref
- 传入的参数必须初始化(赋值)
- 方法内可读可写
out
- 传入前**可以不初始化**
- 方法内**必须赋值**,否则编译报错
- 解决“函数内部改了值,函数外部也要同步变化”的需求
- 让方法可以直接操作调用方变量
区别
1. `ref`
- 传入前必须先初始化
- 方法内可以读,也可以写
2. `out`
- 传入前可以不初始化
- 方法返回前必须赋值
- 常用于“额外带回一个结果”
语法:
在函数传参时,两边都要加上修饰词
ref
```Csharp
//交换数字
void Swap(ref int a, ref int b)
{
int temp = a; a = b; b = temp;
}
定义和调用两边都要写关键字。
`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
//最经典: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`
```csharp
bool TryGetAge(string text, out int age)
{
return int.TryParse(text, out age);
}
if (TryGetAge("18", out int value))
{
Console.WriteLine(value);
}
```
案例:
原型在[[值类型和引用类型]]笔记中
注意:
==out不是用来让内外值一定不等==
==ref传入的参数必须初始化==
如果传入引用类型且内外不同,推荐new一个
1. ==`ref` 参数必须先初始化==
2. ==`out` 参数在方法结束前必须赋值==
3. `ref` / `out` 传的是变量本身,所以修改会影响外部
4. 对引用类型来说:
- 不加 `ref` 时,方法里可以改对象内容
-`ref` 时,连“变量指向哪个对象”都可以改
5. 属性、常量、表达式一般不能直接当 `ref` / `out` 参数传入
#基础
#基础