Skip to main content
 首页 » 编程设计

c#之是否可以两次使用占位符字符串

2024年02月06日21dyllove98

namespace ConsoleApplication3 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Console.WriteLine("Type a number"); 
            ConsoleKeyInfo KeyInfo1 = Console.ReadKey(); 
            Console.WriteLine("Type another number"); 
            ConsoleKeyInfo KeyInfo2 = Console.ReadKey(); 
            Console.WriteLine("The number is {0}", KeyInfo1.KeyChar.ToString() + "The time is {1}. Is this right? Press y for yess or n for no.", KeyInfo2.KeyChar.ToString()); 
            Console.ReadKey(); 
        } 
    } 
} 

我问这个问题的原因是第一个数字显示在控制台中,但第二个数字没有显示,它只是显示 {1}。我希望这是有道理的,我是编程新手。

请您参考如下方法:

WriteLine 函数的第一个参数是格式字符串。
那是您添加占位符的部分。
在第一个格式参数之后添加值以替换占位符作为参数,如下所示:

Console.WriteLine("The number is {0} The time is {1}. Is this right? Press y for yess or n for no.", KeyInfo1.KeyChar.ToString(), KeyInfo2.KeyChar.ToString()); 

第一个参数(在格式之后,即传入函数的第二个参数)将替换 {0},第二个参数将替换 {1}。