// 示例代码:C# 格式化字符串
using System;
class Program
{
static void Main()
{
// 定义变量
string name = "Alice";
int age = 30;
double height = 1.65;
// 使用字符串插值(C# 6.0 及以上版本)
string formattedString1 = $"{name} is {age} years old and {height:F2} meters tall.";
Console.WriteLine(formattedString1);
// 使用 string.Format 方法
string formattedString2 = string.Format("{0} is {1} years old and {2:F2} meters tall.", name, age, height);
Console.WriteLine(formattedString2);
// 使用复合格式化(早期版本)
Console.WriteLine("{0} is {1} years old and {2:F2} meters tall.", name, age, height);
}
}
$
符号和 {}
来插入变量值,语法简洁直观。string.Format
方法进行格式化,适合需要动态生成格式化字符串的场景。Console.WriteLine
中使用格式化字符串,适用于简单的输出。每种方法都可以根据具体需求选择使用。
上一篇:c# 字典排序
下一篇:c# 事件与委托使用场景
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站