简体   繁体   中英

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:

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.

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). 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 + "). Fromat is more readeble than concatenating . In your case 4 arguments:

{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"):

{"icon":"notificationicon","alert":"SomeGovernanceName","governanceType":"SomeGovernanceType"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM