Ric*_*rdo 81 c# string formatting
在这样的字典中:
Dictionary<string, string> openWith = new Dictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
Run Code Online (Sandbox Code Playgroud)
输出是:
对于Key ="rtf"value = wordpad.exe
什么{0}
意思?
Dan*_*ant 176
您正在打印格式化的字符串.{0}表示在格式字符串后插入第一个参数; 在这种情况下,与键"rtf"相关联的值.
对于String.Format,类似的,如果你有类似的东西
// Format string {0} {1}
String.Format("This {0}. The value is {1}.", "is a test", 42 )
Run Code Online (Sandbox Code Playgroud)
你要创建一个字符串"这是一个测试.值是42 ".
您还可以使用表达式,并多次打印值:
// Format string {0} {1} {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1, 1+1, 1+2)
Run Code Online (Sandbox Code Playgroud)
得到"FIB:1,1,2,3 "
有关复合格式的更多信息,请参阅http://msdn.microsoft.com/en-us/library/txafckwd.aspx.
Ste*_*itt 25
它是字符串中的占位符.
例如,
string b = "world.";
Console.WriteLine("Hello {0}", b);
Run Code Online (Sandbox Code Playgroud)
会产生这个输出:
Hello world.
Run Code Online (Sandbox Code Playgroud)
此外,您可以拥有任意数量的占位符.这也适用于String.Format
:
string b = "world.";
string a = String.Format("Hello {0}", b);
Console.WriteLine(a);
Run Code Online (Sandbox Code Playgroud)
你仍然会得到相同的输出.
为了将来参考,在Visual Studio中,您可以尝试将光标放在方法名称中(例如,WriteLine),然后按下F1以获取该上下文的帮助.String.Format()
在这种情况下,挖掘应该找到你,有很多有用的信息.
请注意,突出显示一个选择(例如,双击或执行拖动选择)并且F1仅执行非上下文字符串搜索(在查找任何有用的内容时往往会很糟糕),因此请确保将光标放在任何位置这个词没有突出显示它.
这对于类和其他类型的文档也很有帮助.
归档时间: |
|
查看次数: |
223082 次 |
最近记录: |