Administrator
发布于 2025-10-15 / 6 阅读
0
0

ref out in param四个参数的用法

在C#中,in关键字有多种用法,主要取决于上下文:

1. 参数修饰符(C# 7.2+)

按引用传递只读参数

public void Process(in int value)
{
    // value 是只读的,不能修改
    Console.WriteLine(value);
    // value = 10; // 编译错误!
}
​
// 调用
int num = 5;
Process(in num);
Process(num);    // 也可以省略 in

案例2:ref交换

using System;
​
class RefExample
{
    // 使用ref参数交换两个变量的值
    static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
    
    static void Main()
    {
        int x = 10;
        int y = 20;
        
        Console.WriteLine($"交换前: x = {x}, y = {y}");
        
        Swap(ref x, ref y);  // 必须使用ref关键字
        
        Console.WriteLine($"交换后: x = {x}, y = {y}");
    }
}

2. foreach 循环中的 in

遍历集合

foreach (var item in collection)
{
    Console.WriteLine(item);
}
​
// 示例
int[] numbers = { 1, 2, 3 };
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

3. LINQ 查询表达式中的 in

from 子句

var query = from student in students
            where student.Age > 18
            select student.Name;
​
// 示例
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
var result = from name in names
             where name.StartsWith("A")
             select name;

4. 泛型接口中的逆变(C# 4.0+)

接口逆变

public interface IComparer<in T>
{
    int Compare(T x, T y);
}
​
// 使用示例
IComparer<Animal> animalComparer = new AnimalComparer();
IComparer<Dog> dogComparer = animalComparer; // 协变,因为 in 修饰符
​
class Animal { }
class Dog : Animal { }

5. 模式匹配中的 in(C# 9.0+)

关系模式

public string GetSize(int value) => value switch
{
    < 0 => "Negative",
    >= 0 and <= 10 => "Small",
    > 10 and <= 100 => "Medium",
    > 100 => "Large",
    _ => "Unknown"
};
​
// 与 in 结合使用
public bool IsInRange(int value) => value is (>= 0 and <= 100);

6. 全局 using 别名(C# 10.0+)

全局 using 别名中的 in

global using System;
global using IntList = System.Collections.Generic.List<int>;
​
// 使用时
var list = new IntList();
list.Add(1);

用法总结

上下文

用途

引入版本

参数修饰符

按引用传递只读参数

C# 7.2

foreach 循环

遍历集合元素

C# 1.0

LINQ 查询

指定数据源

C# 3.0

泛型接口

支持逆变

C# 4.0

模式匹配

关系模式检查

C# 9.0

全局 using

类型别名的一部分

C# 10.0

实际示例

// 综合示例
public class Example
{
    // 1. 参数修饰符
    public void ProcessData(in LargeStruct data)
    {
        // 只读访问大数据结构
    }
    
    // 2. foreach 使用
    public void PrintAll(IEnumerable<string> items)
    {
        foreach (var item in items)  // foreach 中的 in
        {
            Console.WriteLine(item);
        }
    }
    
    // 3. LINQ 使用
    public void LinqExample()
    {
        var numbers = new[] { 1, 2, 3, 4, 5 };
        var evens = from num in numbers  // LINQ 中的 in
                    where num % 2 == 0
                    select num;
    }
}

in关键字在C#中的含义会根据使用上下文而变化,从最早的foreach循环到最新的参数修饰符,它的功能在不断扩展。


评论