c# - DRY 字符串格式

标签 c# string.format formatexception

将 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/

相关文章:

c# - 将文件下载到 Azure 函数应用程序进行操作

python - 有没有办法将列表插入到 python 中的 .format 方法中?

c# - FormatException 字符串的长度必须正好是一个字符

java - 嵌套的 If/Else 语句

c# - 我需要在 C# 中编写一个大端单精度 float 到文件

c# - 在 C# : extracting all URLs 中解析 CSS

c# - 当涉及到 MessageBox 时,String.Format() 的对齐方式表现不同

c# - WPF FontFamily格式问题

c# - 有没有办法在 VB.NET 中知道是否已为事件注册了处理程序?

.net - 在 String.Format() 中转义单引号