C# String.Format:输入字符串的格式不正确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14573650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:19:07  来源:igfitidea点击:

String.Format: Input string was not in a correct format

c#.netexception-handlingstring.format

提问by jamesdeath123

The following code keep giving me error saying Input string was not in a correct format, but I am pretty sure it is right, isn't it?

下面的代码一直给我错误提示输入字符串的格式不正确,但我很确定它是正确的,不是吗?

int id = 112;

String[] newData = { "1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa", 
                      "Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1", 
                      "true", "note note note", "true", "1", "2011-12-03", "45"};

String data = "{ cmd: \"save magellan deal\", data: { id: {0} , AId: {1}, " +
            "CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
            "LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
            "dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
            "period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},} " +
            "Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} } }";


String cmd = String.Format(data, id.toString(), newData);

Anyone any ideas?

有人有什么想法吗?

=== EDIT ===

=== 编辑 ===

after fixing the braces, a new error of "Index (zero based) must be greater than or equal to zero and less than the size of the argument list." is given. the newData has 21 and plus the id.toString(), should be exact 22?

修复大括号后,出现“索引(基于零)必须大于或等于零且小于参数列表的大小”的新错误。给出。newData 有 21,加上 id.toString(),应该是 22?

采纳答案by Cédric Bignon

Escape the "{", "}" (by duplicating them) in the format string:

转义格式字符串中的“{”、“}”(通过复制它们):

"{{ cmd: \"save magellan deal\", data: {{ id: {0} , AId: {1}, " +
"CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
"LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
"dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
"period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},}} " +
"Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} }} }}"

And you have 22 elements in the format string and 21 in the array.

格式字符串中有 22 个元素,数组中有 21 个元素。

回答by Eric J.

You have 21 elements in newDatabut use 22 placeholders (numbered 0 to 21).

您在newData 中有 21 个元素,但使用了 22 个占位符(编号为 0 到 21)。

Also, you must escape literal '{' in your input data

此外,您必须在输入数据中转义文字 '{'

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.

开始和结束大括号被解释为开始和结束格式项。因此,您必须使用转义序列来显示文字左大括号或右大括号。在固定文本中指定两个左大括号(“{{”)以显示一个左大括号(“{”),或两个右大括号(“}}”)以显示一个右大括号(“}”)。格式项中的大括号按照它们遇到的顺序依次解释。不支持解释嵌套的大括号。

http://msdn.microsoft.com/en-us/library/txafckwd.aspx

http://msdn.microsoft.com/en-us/library/txafckwd.aspx

回答by Mark Hall

In addition to escaping your curly braces also try changing your String[]definition to:

除了转义大括号外,还可以尝试将String[]定义更改为:

int id = 112;

String[] newData = {id.ToString(), "1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa", 
          "Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1", 
          "true", "note note note", "true", "1", "2011-12-03", "45"};

and change your String.Formatto:

并将您的更改String.Format为:

String cmd = String.Format(data,newData);

回答by George

What

什么

String cmd = String.Format(data, id.toString(), newData);  

does is: trying to format the String data , using just 2 strings..not 22!!
Which ones?...1)id.ToString() and 2)newData.ToString()
Thats obviously wrong

做的是:尝试格式化字符串数据,只使用 2 个字符串..不是 22!
哪些?...1)id.ToString() 和 2)newData.ToString()
那显然是错误的

How you can see that this is the problem...? Leave just {0} and {1} in data string and print it.It compiles ok and see what you get.
Of course you have to use {{ instead of { where you want a string literal

你怎么能看出这是问题所在......?在数据字符串中只留下 {0} 和 {1} 并打印它。它编译正常,看看你得到了什么。
当然,您必须使用 {{ 而不是 { 在您想要字符串文字的地方

Fully working Solution:

完全有效的解决方案:

int id = 112;

String[] newData = { id.ToString(),"1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa", 
                  "Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1", 
                  "true", "note note note", "true", "1", "2011-12-03", "45"};

String data = "{{ cmd: \"save magellan deal\", data: {{ id: {0} , AId: {1}, " +
                    "CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
                    "LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
                    "dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
                    "period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},}} " +
                    "Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} }} }}";


String cmd = String.Format(data, newData);

回答by Eamon Nerbonne

I've said as much in the comments, but I think it's worth an answer by now:

我在评论中说了那么多,但我认为现在值得回答:

Don't use string.Format(in this case). It's slower, and less readable. Just use plain string concatenation with meaningful variable names if you need complex concatenations - these will be faster and more maintainable. Faster because for a fixed number of segments plain +is the fastest optiondue to compiler optimizations, and more maintainable because the reader can see the context within the string in which the variable is put.

不要使用string.Format(在这种情况下)。它更慢,可读性更差。如果您需要复杂的连接,只需使用带有有意义的变量名称的普通字符串连接 - 这些将更快且更易于维护。更快,因为对于固定数量的段,由于编译器优化,plain+最快的选项,并且更易于维护,因为读者可以看到变量所在字符串中的上下文。

As Hans Passant noted, it looks like you're making a javascript literal. If that's the case, consider a Json serializer like Json.NETinstead:

正如 Hans Passant 所指出的,看起来您正在制作一个 javascript 文字。如果是这种情况,请考虑使用像Json.NET这样的 Json 序列化程序:

JsonConvert.SerializeObject(new {
    cmd = "save magellan deal",
    data = new {
        id = 12345, AId = 1, CId = 2, CCId = 21,
        LA = "reidb", BA = "reidb", LSA = "reidb", BSA = "reidb",
        path = "aa", dscp = "Some description", SI = 11,
        CD = "2012-02-28", period = "2012-01-29",
        IsStatic = true, LSD = 1, LC = 1, RB = true,
    },
    Notes = "note note note",
    IsEE = true, RBy = 1, DPDD = "2011-12-03", LId = 45
})

While Json.NETdoes support DateTimeserialization, there's not standardized format for dates in JS, so these are serialized as strings in an iso 8601 format. This might not be what you need, hence the date strings in this example - I'd try the iso format first, though, as that's the simplest solution.

虽然Json.NET确实支持DateTime序列化,但 JS 中的日期没有标准化的格式,因此将它们序列化为 iso 8601 格式的字符串。这可能不是您需要的,因此本示例中的日期字符串 - 不过我会先尝试 iso 格式,因为这是最简单的解决方案。