DateTime.Now和NullReferenceException

时间:2010-02-18 13:46:36

标签: c# datetime

在我的业务对象中,我必须获取当前小时(具有分钟和秒的日期时间= 0)。

我创建了一个这样的函数:

private DateTime GetCurrentHour() 
{ 
        return DateTime.Today.AddHours(DateTime.Now.Hour); 
} 

如果我以这种方式使用它

var lastHour=GetCurrentHour();

我收到NullReferenceException ????

以这种方式使用相同的功能:

var ora = new NHRepository<OraProduzione>(Session) 
               .First(x => x.Data == GetCurrentHour().AddHours(-1)); 

我也不例外 为什么?

这是堆栈跟踪:

   in ImpelSystems.Produzione.Business.Calendario.TimerWakeUp() in \Calendario.cs:riga 115
   in ImpelSystems.Produzione.Business.Calendario.<.ctor>b__1(Object x) in \Calendario.cs:riga 78
   in System.Threading._TimerCallback.TimerCallback_Context(Object state)
   in System.Threading.ExecutionContext.runTryCode(Object userData)
   in System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   in System.Threading._TimerCallback.PerformTimerCallback(Object state)

在使用

创建的定时器上执行TimerWakeUp
timer = new System.Threading.Timer(x => TimerWakeUp(), null, new TimeSpan(0, 0, 0, 10), new TimeSpan(0, 0, 0, 10));

1 个答案:

答案 0 :(得分:1)

您确定您的例外是var lastHour=GetCurrentHour();吗? DateTime类型是一个结构,它应该使它(除非我遗漏某些东西)不可能遇到空引用。

此外,我假设您的意思是DateTime.Today.AddHours(DateTime.Now.Hour),因为Today属性是静态的,因此您无法从Now返回的实例访问它。