命名参数 - 在 C# 中使用 Console.WriteLine

5

我经常写一个Console.WriteLine语句,然后在以后修改它。然后我就会得到这样的语句。

Console.WriteLine("{2} is not greater than {0} or smaller than {1}",min,max, grade);

有没有一种方法可以明确地命名传递给Console.WriteLine的参数,以便我不需要按顺序传递min、max和grade?

另外,我经常在Console.WriteLine中删除要打印的变量,例如下面的示例,其中{2}已被删除。

Console.WriteLine("{3} is not greater than {0} or smaller than {1}",min,max, grade);

有没有不改变编号的方法,可以这样说:
Console.WriteLine("{3} is not greater than {0} or smaller than {1}",{0}:min,{1}:max, {3}: grade);

类似于这样的语句

@Html.ActionLink("Your profile", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" });

使用C# 6字符串插值:$"{grade}不是更大的..." - CodeCaster
为什么不使用字符串插值? $"{grade} 不大于 {min} 或者不小于 {max}" - Stuart
请注意,在字符串中没有自动完成。 - Drag and Drop
2个回答

9

不要这样写:

Console.WriteLine("{3} is not greater than {0} or smaller than {1}",min,max, grade);

您也可以使用C# 6的字符串插值语法:
Console.WriteLine($"{grade} is not greater than {min} or smaller than {max}");

0

可以的。

现在你可以像这样输入字符串

Console.WriteLine($"{grade} is not greater than {max} or smaller than {min}");

请注意字符串前面的美元符号。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接