在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);
用法总结
实际示例
// 综合示例
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
循环到最新的参数修饰符,它的功能在不断扩展。