开发者

DateTime.Now and NullReferenceException

In my business object I have to obtain the current hour (a DateTime with minutes and seconds = 0).

I have created a function like this:

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

If I use it in this way

var lastHour=GetCurrentHour();

I get a NullReferenceException ????

Using in the same function in this way:

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

I get no exception Why?

This is the stacktrace:

   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 开发者_C百科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 is executed on a Timer created with

timer = new System.Threading.Timer(x => TimerWakeUp(), null, new TimeSpan(0, 0, 0, 10), new TimeSpan(0, 0, 0, 10));


Are you certain that your exception is on var lastHour=GetCurrentHour();? The DateTime type is a struct, which should make it (unless I'm missing something) impossible for you to encounter a null reference.

Additionally, I'm assuming you meant DateTime.Today.AddHours(DateTime.Now.Hour), as the Today property is static, so you couldn't access it from the instance returned from Now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜