使用“ in”参数修饰符传递文字

Vad*_* S. 2 c#

目前尚不清楚为什么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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*ane 5

C#语言参考中所指定,您不能将带有in关键字的常量用作参数:

in中使用的参数必须表示可以直接引用的位置。适用于out和ref参数的相同通用规则:不能使用常量,普通属性或其他产生值的表达式。