C#命令行程序问题:如何用单引号包裹用户输入输出错误提示
解决C# CMD程序中错误提示的单引号包裹问题
要实现将用户输入内容用单引号包裹的错误提示,你可以用以下几种简洁的方式:
方法1:字符串拼接
直接将单引号作为字符串片段和变量拼接:
Console.Write("'" + input + "' is not recognized as an internal or external command,\noperable program or batch file.");
方法2:字符串插值(推荐)
C# 6及以上版本支持的字符串插值语法,写法更直观:
Console.Write($"'{input}' is not recognized as an internal or external command,\noperable program or batch file.");
方法3:逐字字符串(适合多行文本)
如果要保留原代码的换行格式,用@前缀的逐字字符串配合插值:
Console.Write($@"'{input}' is not recognized as an internal or external command, operable program or batch file.");
为什么之前的写法无效
- 用
\'input +时,你是把转义的单引号和字符串"input"拼接,而非变量input的实际值; - 用
'input' +时,你拼接的是固定字符串'input',不是用户输入的内容。
内容的提问来源于stack exchange,提问作者ME_B4RT3K
相关产品推荐
相关产品推荐

