如何用 C# 输出变量的值
在 C# 中,可以通过多种方式输出变量的值,以下是最常用的方法:
1. Console.WriteLine()
<code class="csharp">// 定义一个变量 int number = 10; // 使用 Console.WriteLine() 输出变量值 Console.WriteLine(number);</code>
输出结果:
<code>10</code>
2. String.Format()
<code class="csharp">// 定义一个变量
string name = "John";
// 使用 String.Format() 格式化输出
string output = String.Format("Name: {0}", name);
// 输出格式化后的字符串
Console.WriteLine(output);</code>输出结果:
<code>Name: John</code>
3. Interpolated Strings
<code class="csharp">// 定义一个变量
int age = 30;
// 使用内插字符串输出变量值
Console.WriteLine($"Age: {age}");</code>输出结果:
<code>Age: 30</code>
4. Debug.WriteLine()
<code class="csharp">// 定义一个变量 double pi = 3.14; // 使用 Debug.WriteLine() 输出变量值(仅用于调试) Debug.WriteLine(pi);</code>
输出结果可在 Visual Studio 的输出窗口中查看。
