C#String.Format可选参数 [英] C# String.Format optional parameters

查看:100
本文介绍了C#String.Format可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将string.Formatoptional 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆