简体   繁体   中英

why does this throw a System.FormatException?

Is this a bug on string.Format or what?

// Act
string l = "This is an UnitTest embedded resource.";
string r = "Please do not remove or change. Sincerely yours, {0}".FormatWith(model.Username);
string expected = "[\r\n\t{0}\r\n\r\n\r\n]\r\n{\r\n\t\r\n\t{1}\r\n\r\n}".FormatWith(l, r);

The FormatWith method is just an extension for syntactic sugar.

public static string FormatWith(this string text, params object[] args)
{
    return string.Format(text, args);
}

Your problem is with trying to use { and } in the format string. They need to be escaped or they will be treated as a format variable.

Change the last line to this:

string expected = "[\r\n\t{0}\r\n\r\n\r\n]\r\n{{\r\n\t\r\n\t{1}\r\n\r\n}}".FormatWith(l, r);

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