简体   繁体   English

DateTime.Now和NullReferenceException

[英]DateTime.Now and NullReferenceException

In my business object I have to obtain the current hour (a DateTime with minutes and seconds = 0). 在我的业务对象中,我必须获取当前小时(具有分钟和秒= 0的DateTime)。

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 ???? 我得到了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 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 TimerWakeUp在使用以下命令创建的计时器上执行

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(); 您确定您的异常在var lastHour=GetCurrentHour();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. DateTime类型是一个结构,应该使它(除非我缺少某些东西)使您不可能遇到空引用。

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 . 另外,我假设您的意思是DateTime.Today.AddHours(DateTime.Now.Hour) ,因为Today属性是静态的,所以您无法从Now返回的实例中访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM