【发布时间】:2020-03-13 18:22:12
【问题描述】:
目前尚不清楚为什么 C# 不允许调用与 in 参数修饰符一起传递文字的方法;同时,当文字传递给没有in 参数修饰符的方法时,代码编译。
这是一个演示此行为的代码示例 (C# 7.3):
class Program
{
static void Main(string[] args)
{
string s = string.Empty;
//These two lines compile
WriteStringToConsole(in s);
WriteStringToConsole("my string");
//Error CS8156 An expression cannot be used in this context because it may not be passed or returned by reference
WriteStringToConsole(in "my string");
}
public static void WriteStringToConsole (in string s)
{
Console.WriteLine(s);
}
}
【问题讨论】:
-
in 关键字导致参数通过引用传递。它使形参成为实参的别名,实参必须是变量。
-
@GoodSamaritan 您应该在评论中添加您引用的链接。
-
调用方法中不需要“in”。方法声明中只需要它。
-
“in”的唯一含义是,防止传递文字和属性。如果您不想阻止它,请不要使用它。
标签: c#