C#/.NET:为何无法将ref readonly变量传入同修饰符的方法?
问题解析与解决方案
先看你提供的代码:
struct Struct { public int Num; } class Program { public void A(ref readonly Struct s) { } public void B(ref readonly Struct s) => A(ref s); }
编译时触发错误:
CS8329: Cannot use variable as a ref or out value because it is a readonly variable
错误原因
ref readonly 参数本质是只读的引用变量:它限制了对引用目标的修改,但这个参数本身在方法内部是只读的。当你尝试直接把它作为 ref 参数传递给另一个方法时,C# 编译器会拦截操作——哪怕目标方法同样声明了 ref readonly,编译器的类型安全检查要求必须确保传递的引用不会被转换为可修改的引用,而直接传递只读的引用变量违反了这个约束。
解决方案
最规范的解决方式是用 in 关键字替代 ref readonly 声明方法参数。in 是C#专门为只读引用传递设计的语法,编译器会自动处理引用的只读传递逻辑,允许在方法间正常传递:
struct Struct { public int Num; } class Program { public void A(in Struct s) { } public void B(in Struct s) => A(s); }
如果一定要保留 ref readonly 写法,可以通过创建临时的只读引用变量来传递,不过这种方式冗余,不推荐:
public void B(ref readonly Struct s) { ref readonly Struct temp = ref s; A(ref temp); }
补充说明
ref readonly 更适合局部变量场景,用来创建指向只读存储位置的引用;而方法参数的只读引用传递,C#官方推荐使用 in 关键字,它语法更简洁,还能规避这类编译错误,同时完全保证参数的只读性。
内容的提问来源于stack exchange,提问作者Yaakov Shoham
相关产品推荐
相关产品推荐

