我有一个 DateTime?
类型的变量
在一个函数中,我检查它是否为 null
并想在以后使用它而不必总是 ?.
每次调用。例如IDE 的 Kotlin 识别这样的检查并断言该变量之后不能为 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# 相信以前可为 null 的变量不再可为 null?
编辑2
在变量上转换 DateTime 是可行的。
TimeSpan span = (DateTime)BFreigabe - DateTime.Now;
仍然不如 Kotlin 安全,但足够相似。
最佳答案
如果你有前面的检查,你可以访问该值。可空类型始终具有两个属性:HasValue
和 Value
。
您可以转换为 DateTime
(没有 ?
)或使用 value 属性。
DateTime? BFreigabe = getDateTime();
if (!BFreigabe.HasValue == null)
return false;
TimeSpan span = BFreigabe.Value - DateTime.Now;
或者将可空变量存储在非可空变量中:
DateTime? BFreigabe = getDateTime();
if (BFreigabe.HasValue == null)
{
DateTime neverNull = BFreigabe.Value;
TimeSpan span = neverNull - DateTime.Now;
}
这将得到完整的编辑器支持并保证没有NullReferenceExcpetion
。
编辑:因为您的问题是断言。 Assert 通常意味着如果状态无效,我们将抛出异常。
在这种情况下,忽略是否为空的检查。如果在 var
为 null 时访问 var.Value
,则会抛出 NullReferenceException
。这将责任转移给调用者。
另一种选择是不使用可空变量。通过转换它(参见第二个 list )或不接受 Nullable 类型作为参数。
function TimeSpan Calc(DateTime time)
{
// here we know for sure, that time is never null
}
关于c# - 断言变量不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45326938/