leo*_*ora 11 c# performance datetime
有没有更快的方法来简单地捕获如下的异常?
try
{
date = new DateTime(model_.Date.Year, model_.Date.Month, (7 * multiplier) + (7 - dow) + 2);
}
catch (Exception)
{
// This is an invalid date
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*l G 15
String DateString = String.Format("{0}/{1}/{2}", model_.Date.Month, (7 * multiplier) + (7 - dow) + 2),model_.Date.Year);
DateTime dateTime;
if(DateTime.TryParse(DateString, out dateTime))
{
// valid
}
Run Code Online (Sandbox Code Playgroud)
正如GenericTypeTea指出的评论一样,这段代码的运行速度不会超过你现在的速度.但是,我相信你获得了可读性.
如果您的目标是避免使用异常,则可以编写自定义验证方法:
public bool IsValidDate(int year, int month, int multiplier, int dow)
{
if (year < 1 | year > 9999) { return false; }
if (month < 1 | month > 12) { return false; }
int day = 7 * multiplier + 7 - dow;
if (day < 1 | day > DateTime.DaysInMonth(year, month)) { return false; }
return true;
}
Run Code Online (Sandbox Code Playgroud)
这与您正在使用的DateTime构造函数执行大多数相同的验证 - 它只省略检查以查看生成的DateTime是否小于DateTime.MinValue或大于DateTime.MaxValue.
如果你大多数都得到了好的值,那么整体上可能会更慢:DateTime.DaysInMonth必须做很多与DateTime构造函数相同的事情,所以它会增加所有好日期的开销.
嗯......按照这种方式思考:model_类有一个DateTime属性
model_.Date
Run Code Online (Sandbox Code Playgroud)
,所以无需验证年份和月份.唯一棘手的部分是每月的某一天:
(7 * multiplier) + (7 - dow) + 2
Run Code Online (Sandbox Code Playgroud)
因此,一种非常快速有效的方法来验证它(这比抛出和捕获更好)是使用DateTime.DaysInMonth方法:
if ((multiplier <= 4) &&
(DateTime.DaysInMonth(model_.Date.Year, model_.Date.Month) <
(7 * multiplier) + (7 - dow) + 2))
{
// error: invalid days for the month/year combo...
}
Run Code Online (Sandbox Code Playgroud)
另一个好处是您不需要实例化新的DateTime来验证此信息.
PS 更新了代码以确保乘数 <= 4.这才有意义,因为任何值> = 5都会使DaysInMonth测试失败...