gpt4 book ai didi

c# - 使用 "in"参数修饰符传递文字

转载 作者:行者123 更新时间:2023-11-30 20:14:49 31 4
gpt4 key购买 nike

目前尚不清楚为什么 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);
}
}

最佳答案

C# language reference 中所述,您不能将常量与 in 关键字一起用作参数:

The argument used with in must represent a location that can be directly referred to. The same general rules for out and ref arguments apply: you cannot use constants, ordinary properties, or other expressions that produce values.

关于c# - 使用 "in"参数修饰符传递文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913593/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com