Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#格式化字符串

作者:叶枫殇   发布日期:2025-05-29   浏览:20

// 示例代码: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);
    }
}

解释说明:

  1. 字符串插值:使用 $ 符号和 {} 来插入变量值,语法简洁直观。
  2. string.Format 方法:通过 string.Format 方法进行格式化,适合需要动态生成格式化字符串的场景。
  3. 复合格式化:直接在 Console.WriteLine 中使用格式化字符串,适用于简单的输出。

每种方法都可以根据具体需求选择使用。

上一篇:c# 字典排序

下一篇:c# 事件与委托使用场景

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站