我是否应该例外阻止用户在字符串中输入{0}或{2}

Joh*_*son 0 c#

像今天一样,我发现这样的事情可能会发生.我把值直接放在字符串中,但让我们说用户把它.更新示例:

   int age = 21; // Users gives age 21
   string s1 = "John {0}"; // Users gives name john and inputs this too {0}

   Console.WriteLine(s1, age); // Me wanting to show his name along with the {0} and the age

Output is :John 21
Outpout wanted is John {0} 21
Run Code Online (Sandbox Code Playgroud)

Pet*_*den 6

如果你这样称呼:

Console.WriteLine("{0} {1}", "John {0}", 21);
Run Code Online (Sandbox Code Playgroud)

(这"{0} {1}"是您提供的格式,而不是用户输入的格式.)

输出将是:

John {0} 21
Run Code Online (Sandbox Code Playgroud)

通过格式化用户输入的数据,大括号不会被视为特殊数据.

在您的代码中,您将其称为:

Console.WriteLine("{0} {1}", s1, age);
Run Code Online (Sandbox Code Playgroud)

  • @GeorgeOscStephan这个答案意味着你不必关心他是否输入`{0}`. (5认同)