in关键字用于传递大型值类型的只读引用,避免复制开销,提升性能。它适用于大型struct的高频调用场景,确保方法内无法修改原始数据,兼具性能与安全。与ref(读写引用)和out(输出引用)不同,in仅用于输入且不可修改,不适用于小型值类型或需修改参数的场景,调用时可省略in但建议显式标注以明确意图。

C#的
in
struct
在C#中,值类型(如
struct
int
bool
struct
in
ref
in
例如:
public struct LargeStruct
{
    public int X;
    public int Y;
    // 更多字段...
    public long[] Data; // 假设这是一个大型数组
}
public void ProcessByValue(LargeStruct data)
{
    // data 是原始数据的一个副本
    // 修改 data 不会影响原始数据
    data.X = 100; 
}
public void ProcessByIn(in LargeStruct data)
{
    // data 是原始数据的只读引用
    // 尝试修改 data.X 会导致编译错误
    // data.X = 100; // 编译错误!
    Console.WriteLine($"Processing data: {data.X}");
}
// 调用示例
LargeStruct myStruct = new LargeStruct { X = 1, Y = 2, Data = new long[1000] };
ProcessByValue(myStruct); // 复制了整个 LargeStruct
Console.WriteLine($"After ProcessByValue: {myStruct.X}"); // 输出 1
ProcessByIn(myStruct); // 传递只读引用
Console.WriteLine($"After ProcessByIn: {myStruct.X}"); // 输出 1in
在我看来,
in
struct
想象一下,你有一个
Vector3D
Matrix4x4
float
double
in
in
使用
in
最佳使用场景:
struct
in
struct
in
struct
in
struct
in
何时不建议使用(或需谨慎):
int
bool
float
Guid
in
in
ref
in
注意事项:
in
in
in
MyMethod(in myStruct)
in
in
const
in
in
in
get
set
in
in
in
ref
out
这三个关键字常常让人混淆,但它们各自有着非常明确且不可替代的职责。在我看来,它们是C#在参数传递机制上提供的三把“瑞士军刀”,各有锋芒。
in
struct
void CalculateSum(in int a, in int b) 
{
    // a = 10; // 编译错误
    Console.WriteLine(a + b); 
}ref
void Swap(ref int x, ref int y)
{
    int temp = x;
    x = y;
    y = temp;
}out
out
Try...Parse
bool TryParse(string s, out int result)
{
    // 尝试解析s
    if (int.TryParse(s, out result))
    {
        return true;
    }
    result = 0; // 必须赋值
    return false;
}总结来说,
in
ref
out
以上就是C#的in关键字有什么作用?如何传递只读引用?的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号