How to get String.Format not to parse {0}

烂漫一生 提交于 2019-12-12 10:02:10

问题


I am writing a code generation tool that frequently will have lines like

StringBuilder sp = new Stringbuilder();
sp.AppendFormat("        public {0}TextColumn()\n", className);
sp.AppendLine("        {"
sp.AppendLine("            Column = new DataGridViewTextBoxColumn();");
sp.AppendFormat("            Column.DataPropertyName = \"{0}\";\n", columnName);

However the issue I am having is when I run in to a line like this.

sp.AppendFormat("return String.Format(\"{0} = '{0}'\", cmbList.SelectedValue);", columnName);

I want the first {0} to turn in to whatever the value of columnName is but I want the seccond {0} to be left alone so the internal String.Format will process it correctly.

How do I do this?


回答1:


Use double curly braces:

string result = string.Format("{{Ignored}} {{123}} {0}", 543);



回答2:


Curly braces can be escaped by using two curly brace characters. The documentation of string.Format states:

To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".

In your example that would be

sp.AppendFormat("return String.Format(\"{0} = '{{0}}'\",cmbList.SelectedValue);", 
    columnName);



回答3:


sp.AppendFormat("return String.Format(\"{0} = '{{0}}'\", cmbList.SelectedValue);", columnName);



回答4:


Use "{{0}}". This will result in the string "{0}"




回答5:


String.Format(\"{0} = '{{0}}'\",


来源:https://stackoverflow.com/questions/3319896/how-to-get-string-format-not-to-parse-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!