温馨提示×

C#中console.writeline的用法有哪些

小亿
198
2023-07-22 13:07:12
栏目: 编程语言

在C#中,Console.WriteLine()方法主要用于在控制台窗口中输出文本或变量的值。以下是一些常见的用法:

  1. 输出字符串:
string message = "Hello World!";
Console.WriteLine(message);
  1. 输出变量的值:
int number = 10;
Console.WriteLine(number);
  1. 输出多个值:
int x = 5;
int y = 3;
Console.WriteLine("x = {0}, y = {1}", x, y);
  1. 输出格式化字符串:
double pi = 3.14159;
Console.WriteLine("The value of pi is {0:F2}", pi);

上述代码将输出 “The value of pi is 3.14”,其中{0:F2}表示将第一个参数格式化为带有两位小数的浮点数。

  1. 输出特殊字符:
Console.WriteLine("This is a \t tab");
Console.WriteLine("This is a \n new line");

上述代码中,\t表示一个制表符,\n表示一个换行符。

  1. 输出对象的字符串表示:
Person person = new Person("John", 25);
Console.WriteLine(person);

上述代码中,Person类的ToString()方法被调用,以输出对象的字符串表示。

这只是Console.WriteLine()方法的一些常见用法,实际上还有其他更多的用法,具体取决于你的需求。

0