将string.format的通用格式(例如,日期时间)提取为可访问的常量的一种优雅方法是什么?
理想情况下,我想执行以下操作,但是在尝试使用此代码时出现以下错误。
var now = DateTime.Now;
var format = "yyyy-MM-dd";
Console.WriteLine(string.Format("The date is {1:{0}}", format, now));
[System.FormatException:输入字符串的格式不正确。]在Program.Main():第9行
其背后的原因是某些API需要特定的日期时间格式。我希望能够引用一个地方来获取该格式,以便所有调用或不进行任何调用。
我意识到下面的方法会起作用,但是看起来不是很优雅。
Console.WriteLine(string.Format("The date is {1:" + format + "}", format, now));
您可以使用应用程序不变的路线-包含格式字符串的静态类。
namespace App.Framework {
public static class AppConstant {
public static readonly string DisplayDateShort = "MM/dd/yyyy";
}
}
就您的例子而言,这是有缺陷的。您想ToString()
利用自己的DateTime
价值。
Console.WriteLine(now.ToString(AppConstant.DisplayDateShort));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句