c# 字符串格式化 [英] c# string formatting

查看:19
本文介绍了c# 字符串格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么我会使用字符串格式,而我可以使用连接,例如

I m curious why would i use string formatting while i can use concatenation such as

Console.WriteLine("Hello {0} !", name);

Console.WriteLine("Hello "+ name + " !");

为什么更喜欢第一个而不是第二个?

Why to prefer the first one over second?

推荐答案

你选的例子太简单了.

字符串格式:

  • 允许您多次使用同一个变量:("{0} + {0} = {1}", x, 2*x)
  • 在其参数上自动调用 ToString:("{0}: {1}", someKeyObj, someValueObj)
  • 允许您指定格式:("The value will be {0:3N} (or {1:P}) on {2:MMMM yyyy gg}", x, y, theDate)
  • 允许您轻松设置填充:(">{0,3}<", "hi");//">hi <"

这篇关于c# 字符串格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆