[英]DateTime.Now and NullReferenceException
在我的業務對象中,我必須獲取當前小時(具有分鍾和秒= 0的DateTime)。
我創建了這樣的函數:
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));
您確定您的異常在var lastHour=GetCurrentHour();
上var lastHour=GetCurrentHour();
? DateTime
類型是一個結構,應該使它(除非我缺少某些東西)使您不可能遇到空引用。
另外,我假設您的意思是DateTime.Today.AddHours(DateTime.Now.Hour)
,因為Today
屬性是靜態的,所以您無法從Now
返回的實例中訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.