假设我正在创建一个同时具有名称和日期的类对象的实例。设置日期时,哪种做法被认为是最佳做法?
var employees = new List<Employee>()
{
new Employee {Name = "Foo", HireDate = new DateTime(2000, 1, 15)},
new Employee {Name = "Bar", HireDate = new DateTime(2001, 5, 25)},
};
或
var employees = new List<Employee>()
{
new Employee {Name = "Foo", HireDate = DateTime.Parse("2000, 1, 15")},
new Employee {Name = "Bar", HireDate = DateTime.Parse("2001, 5, 25")},
};
我假设确实没有太大区别,但我对 C# 有点陌生,所以我不确定大多数 C# 程序员更喜欢哪个以及为什么(性能、可读性等)。提前感谢您提供的任何见解!
最佳答案
首选新日期时间
。
支持 new
,它将允许您直接使用变量:
// clean because the variable is applied directly to the function
int year = 2000;
var date1 = new DateTime(year, 1, 15);
var date1 = new DateTime(year, 7, 3);
var date1 = new DateTime(year, 8, 19);
// kind of gross and prone to errors because it is appended to the string
int day = 23;
var date1 = DateTime.Parse("2001, 5, " + day.ToString());
在反对 Parse
的论点中,它直到运行时才检测到错误:
var date1 = new DateTime(200fdsa, 1, 15); // Error on compile
var date2 = DateTime.Parse("2001fdsjf, 5, 25"); // Must run to find the error
DateTime.Parse
的性能总是较差,因为它需要运行检测错误并将字符串转换为数值的代码。它会在您的程序运行时执行此操作。
但是 - 在您必须接受字符串输入的情况下(例如来自文本文件),您应该使用为此工作构建的工具:DateTime.Parse
。
如果您对简化代码中日期/时间常量的规范感兴趣,可以使用 Jon Skeet 为此编写的库。
它有点陈旧且无人维护,但具体代码(整数常量/日期和时间结构上的扩展方法)可能不需要太多维护。
这些扩展的源代码位于 MiscUtil\MiscUtil\Extensions\TimeRelated\
下(在源 zip 中)
它可以让您以更友好的方式编写日期时间,但仍会为您提供性能与 new DateTime(2012, 11, 13)
类似的干净代码:
DateTime someDateAndTime = 19.June(1976) + 8.Hours();
关于c# - 最佳实践 : new DateTime() vs DateTime. Parse(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8108806/