[英]Demistify string.format in C#
I know what I'm going to ask is silly. 我知道我要问的是愚蠢的。 So here it goes.
所以就到这里。 I have a C# code where I have a string as shown below:
我有一个C#代码,其中有一个字符串,如下所示:
string.Format(
"{0}\"icon\":\"{2}\",\"alert\":\"{3}\",\"governanceType\":\"{4}\"{1}",
"{",
"}",
"notificationicon",
governanceName,
tips.GovernanceType)
Would any one explain would the above code mean. 任何人都可以解释以上代码的含义吗?
String.Format
replaces tokens in a string with the values denoted the zero-based index of subsequent parameters. String.Format
将字符串中的标记替换为表示后续参数的从零开始的索引的值。
Comments added for clarity: 为了清楚起见添加了注释:
string.Format(
"{0}\"icon\":\"{2}\",\"alert\":\"{3}\",\"governanceType\":\"{4}\"{1}",
"{", // {0}
"}", // {1}
"notificationicon", // {2}
governanceName, // {3}
tips.GovernanceType)// {4}
However, the brace values are presumably only there to avoid an error. 但是,大括号值大概只是为了避免错误。 A clearer solution is to escape them:
一个更清晰的解决方案是逃避它们:
string.Format(
"{{\"icon\":\"{0}\",\"alert\":\"{1}\",\"governanceType\":\"{2}\"}}",
"notificationicon", // {0}
governanceName, // {1}
tips.GovernanceType)// {2}
As explained in the comments, the first parameter is the string to be formatted, and all subsequent parameters will be inserted at the locations of the placeholders, denoted by {x}
in the format string (where x is an indexing integer). 如注释中所述,第一个参数是要格式化的字符串,所有后续参数将插入占位符的位置,在格式字符串中用
{x}
表示(其中x是索引整数)。 The frequent \\
s in the format string are escape characters that prevent inline "
-characters from ending the string (they are instead printed literally). 格式字符串中的常用
\\
是转义字符 ,可防止内联"
字符结束字符串(而是按原样打印)。
Format allow to build string with arguments in {} instead of concatenating ("+ var + "). 格式允许使用{}中的参数构建字符串,而不是串联(“ + var +”)。 Fromat is more readeble than concatenating .
Fromat比连接更容易阅读。 In your case 4 arguments:
在您的情况下,有4个参数:
{0} = "{"
{1} = "}"
{2} = "notificationicon"
{3} = value of governanceName
{4} = value of tips.GovernanceType
Finally arguments {} will replaced by values and you will get new frormatted string 最后,参数{}将被值替换,您将获得新的带字符串的字符串
To make it more readable and comprehensible I have replaced the "
char with the '
char. The command could be thus simplified like this: 为了使其更易于阅读和理解我已经取代了
"
用字符'
字符的命令可以简化因而是这样的:
string.Format("{{'icon':'notificationicon','alert':'{0}','governanceType':'{1}'}}",
governanceName, tips.GovernanceType);
When I add .Replace('\\'','\\"')
to it then it produces following string (assuming that governanceName="SomeGovernanceName", tips.GovernanceType="SomeGovernanceType"): 当我向其中添加
.Replace('\\'','\\"')
,它会产生以下字符串(假设GovernanceName =” SomeGovernanceName“,tips.GovernanceType =” SomeGovernanceType“):
{"icon":"notificationicon","alert":"SomeGovernanceName","governanceType":"SomeGovernanceType"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.