断言variables不是空的

我有一个types为DateTime?的variablesDateTime?

在一个函数中,我检查它是否为null并希望事后使用它,而不必一直使用它?. 每一个电话。 在例如Kotlin中,IDE识别出这样的检查,并断言该variables之后不能为null 。 有没有办法在C#中做到这一点?

 DateTime? BFreigabe = getDateTime(); if (BFreigabe == null) return false; TimeSpan span = BFreigabe - DateTime.Now; //Shows Error because it.BFreigabe has the type DateTime?, even though it can't be null 

编辑:

使用时

 TimeSpan span = BFreigabe.Value - DateTime.Now; 

相反,它在这种情况下工作因为.Value根本没有任何的安全。 然而,考虑到即使没有空检查也会编译,只是产生一个错误,一般的问题仍然存在。 如何说服C#前一个可空variables不能再空?

编辑2

在variables上投射日期时间。

 TimeSpan span = (DateTime)BFreigabe - DateTime.Now; 

仍然不如Kotlin那样安全,但是足够相似。

如果您有以前的检查,您可以访问该值。 可空types总是有两个属性: HasValueValue

你可以投到DateTime (没有? )或使用value属性。

 DateTime? BFreigabe = getDateTime(); if (!BFreigabe.HasValue == null) return false; TimeSpan span = BFreigabe.Value - DateTime.Now; 

或者将可为空的variables存储在一个不可为空的variables中:

 DateTime? BFreigabe = getDateTime(); if (BFreigabe.HasValue == null) { DateTime neverNull = BFreigabe.Value; TimeSpan span = neverNull - DateTime.Now; } 

这将得到完整的编辑器支持,并保证没有NullReferenceExcpetion

编辑 :因为你的问题状态断言 。 断言通常意味着我们将抛出一个exception的状态是无效的。

在这种情况下,省略检查nullness。 如果在var为null时访问var.Value ,则会抛出NullReferenceException 。 这将责任移交给呼叫者。

另一个选择是不使用可空variables。 可以通过转换(参见第二个列表)或不接受Nullabletypes作为参数。

 function TimeSpan Calc(DateTime time) { // here we know for sure, that time is never null } 

这个怎么样?

 DateTime? BFreigabe = getDateTime(); if (!BFreigabe.HasValue) return false; DateTime BFreigabeValue = BFreigabe.Value; TimeSpan span = BFreigabeValue - DateTime.Now; 

尝试将NULL值转换为任何值,这是无关紧要的。

 DateTime? BFreigabe = getDateTime(); if (BFreigabe == null) return false; TimeSpan span = (BFreigabe??DateTime.Now) - DateTime.Now;