寻找一种更简单的方法 - 以及更美观的方法
您将如何重写以下内容,以便看起来更容易一些?
Func<DateTime, String> formatter = null;
formatter = new Func<DateTime, String>(d =>
{
var r = "";
foreach (var i in new[] { d.Day, d.Month, d.Year })
{
if (i < 10) r += "0";
r += i.ToString();
}
return r;
});
How would you re-write the following, so it's a bit easier on the eyes?
Func<DateTime, String> formatter = null;
formatter = new Func<DateTime, String>(d =>
{
var r = "";
foreach (var i in new[] { d.Day, d.Month, d.Year })
{
if (i < 10) r += "0";
r += i.ToString();
}
return r;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我将其重写为:
这里唯一的区别是,对于公元 1000 年之前的日期,这将填充到 4 位数字而不是 2 位...
编辑:如注释中所述,这不会复制原始代码中的错误 - 它会将月份 5 格式(例如)为“055”。在原始代码中解决此问题的最简单方法是:(
但无论如何我更喜欢我的代码:)
I'd rewrite it as:
Only difference here is that for dates before 1000AD, this will pad to 4 digits instead of 2...
EDIT: As noted in comments, this doesn't replicate the bug in the original code - it would format (say) a month of 5 as "055". The simplest way to fix this in the original code would be:
(But I'd prefer my code anyway :)
我最喜欢 Jon Skeets 的回答,但我想提供另一种选择:
我总是检查此网站的字符串格式:http://blog.stevex.net/string-formatting-in-csharp/
I like Jon Skeets answer best, but I'd like to offer an alternative:
I always check this site for string formatting: http://blog.stevex.net/string-formatting-in-csharp/
有什么理由不将整个格式化程序代码与
ToString("ddMMyyyy")
交换?Any reason not to exchange the entire formatter code with a
ToString("ddMMyyyy")
?