C#String.Format可选参数 [英] C# String.Format optional parameters
问题描述
我想将string.Format
与optional parameters
一起使用:
public static void Main(string[] args)
{
// Your code goes here
// Console.WriteLine(string.Format("{0} {1}", "a", "b"));
Console.WriteLine(string.Format("{0} {1}", "a"));
}
例如,参数{1}
是可选的并具有默认值
for exemple the parameter {1}
to be optional and to have a default value
你能帮我做到这一点吗?
Can you help me to do this?
推荐答案
这取决于您所说的可选参数".
It depends on what you mean by "optional parameter".
如果要自动将null
替换为默认值,最简单的方法是在参数内使用null合并运算符:
If you want to automatically replace null
with a default value, the easiest way to do that is to use the null coalescing operator inside the arguments:
String.Format("{0} {1}",
"a",
someNullableVariableContainingB ?? "default value");
如果您想对多个String.Format调用重复使用相同的格式字符串,例如
If you want to reuse the same formatting string for multiple String.Format invocations, e.g.
var myFormatString = "{0} {1}";
var string1 = String.Format(myFormatString, "a", "b");
var string2 = String.Format(myFormatString, "a");
那么您就不走运了:如果参数太少,String.Format 将引发异常 提供,并且无法在格式字符串内指定可选参数".您将不得不使用String.Format之外的其他方法,例如,一个自定义方法,该方法将缺失的参数替换为其预期的默认值.
then you are out of luck: String.Format will throw an exception if too few arguments are provided, and there's no way to specify an "optional parameter" inside the format string. You will have to use something other than String.Format, for example, a custom method which replaces missing arguments with their intended default values.
这篇关于C#String.Format可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!