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

查看:126
本文介绍了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)

  • 允许你指定的格式:(以下简称值将是{0:3N}(或{1:P}:X,Y,theDate)

  • 让你轻松设置填充:<$ C对{MMMM YYYY GG 2}) $ C>(> {0,3}<,喜); //>喜<

  • allows you to use the same variable multiple times: ("{0} + {0} = {1}", x, 2*x)
  • automatically calls ToString on its arguments: ("{0}: {1}", someKeyObj, someValueObj)
  • allows you to specify formatting: ("The value will be {0:3N} (or {1:P}) on {2:MMMM yyyy gg}", x, y, theDate)
  • allows you to set padding easily: (">{0,3}<", "hi"); // ">hi <"

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

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