String.Format扩展方法

Sin*_*atr 6 c# extension-methods coding-style

我有:

public static string Format(this string text, params object[] args)
{
   return string.Format(text, args);
}
Run Code Online (Sandbox Code Playgroud)

所以我可以这样做:

"blablabla {0}".Format(variable1);
Run Code Online (Sandbox Code Playgroud)

这是好事还是坏事?它会变得更短吗?我希望无缝地构建字符串,比如编写文本而不必担心参数和内容之前或之后:

// bad
return "date: " + DateTime.Now.ToString("dd.MM.yyyy") + "\ntime: " + DateTime.Now.ToString("mm:HH:ss") + "\nuser: " + _user + " (" + _status + ")";

// better, but you have to deal with order of {0}...{n} and order of parameters
return string.Format("date: {0}\ntime: {1}\user: {2} ({3})", ...);

// ideal
return "date: {DateTime.Now{dd:MM:yyyy}}\ntime: {...}\nuser: {_user} ({_status})";
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 3

好吧,有一件坏事是,通过只有一个params object[]方法,您会在每次调用时强制进行额外的数组分配。

您可能会注意到,string.Format有一系列用于获取少量参数的重载(这些重载非常常用) - 我建议复制它们。

您的“理想”场景可以通过重写该string.Format方法来完成,但您需要传入值,即

return "date: {date}\ntime: {...}\nuser: {_user} ({_status})"
     .Format(new { date = DateTime.Now, _user, _status });
Run Code Online (Sandbox Code Playgroud)

(并使用您自己的自定义Format方法,或类似的方法) - 但请注意,这会强制每次调用一个新的对象实例。

实际上,单声道编译器曾经有一个实验标志可以直接启用此功能。不知道有没有维护。