将 string.format 的通用格式(例如日期时间)提取为可访问常量的优雅方法是什么?
理想情况下,我想执行如下操作,但当我尝试使用此代码时出现以下错误。
var now = DateTime.Now;
var format = "yyyy-MM-dd";
Console.WriteLine(string.Format("The date is {1:{0}}", format, now));
[System.FormatException: Input string was not in a correct format.] at Program.Main(): line 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";
}
}
就您的示例而言,它存在一些缺陷;你想在你的 DateTime
值上调用 ToString()
。
Console.WriteLine(now.ToString(AppConstant.DisplayDateShort));
关于c# - DRY 字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770307/