C# DateTime.Now和NullReferenceException

C# DateTime.Now和NullReferenceException,c#,datetime,C#,Datetime,在我的业务对象中,我必须获取当前的小时(一个分秒为0的日期时间) 我创建了这样一个函数: private DateTime GetCurrentHour() { return DateTime.Today.AddHours(DateTime.Now.Hour); } 如果我这样使用它 var lastHour=GetCurrentHour(); 我得到一个NullReferenceException ???? 以这种方式在同一功能中使用: var ora = new

在我的业务对象中,我必须获取当前的小时(一个分秒为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)); 

您确定您的异常在
var lasthhour=getcurrenthhour()上吗
DateTime
类型是一个结构,它应该使您不可能遇到空引用(除非我遗漏了什么)


另外,我假设您的意思是
DateTime.Today.AddHours(DateTime.Now.Hour)
,因为
Today
属性是静态的,所以您无法从
Now

返回的实例访问它。您确定您的异常是在
var lastHour=GetCurrentHour()上吗
DateTime
类型是一个结构,它应该使您不可能遇到空引用(除非我遗漏了什么)


另外,我假设您指的是
DateTime.Today.AddHours(DateTime.Now.Hour)
,因为
Today
属性是静态的,所以您无法从
Now
返回的实例访问它,您可以像这样获取当前小时数DateTime.Now.Hour为什么要使用这个DateTime.AddHour(DateTime.Now.Hour)?您确定该行发生异常吗?该方法中没有任何内容可以引发NullReferenceException…异常位于var lastHour=GetCurrentHour()上;Visual Studio停在那里…你能发布堆栈跟踪吗?你能发布
TimerWakeUp
的代码吗?你可以像这样获取当前的小时数DateTime.Now.hour为什么今天要使用这个。AddHour(DateTime.Now.hour)?你确定该行发生异常吗?该方法中没有任何内容可以引发NullReferenceException…异常位于var lastHour=GetCurrentHour()上;Visual Studio停在那里…您可以发布堆栈跟踪吗?您可以发布
TimerWakeUp
?+1的代码吗。请注意,GetCurrentHour()和DateTime都不会显示在堆栈跟踪中。+1。请注意,GetCurrentHour()和DateTime都不会显示在堆栈跟踪中。
   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)
timer = new System.Threading.Timer(x => TimerWakeUp(), null, new TimeSpan(0, 0, 0, 10), new TimeSpan(0, 0, 0, 10));