【发布时间】:2019-12-03 19:30:32
【问题描述】:
在下面的示例中,有没有一种方法可以更简洁地将可空引用类型转换为不可空引用类型?
这适用于编译器的可为空引用标志启用时。
当可空引用类型为null时,我希望它抛出异常。
Assembly? EntryAssemblyNullable = Assembly.GetEntryAssembly();
if (EntryAssemblyNullable is null)
{
throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");
}
Assembly EntryAssembly = EntryAssemblyNullable;
var LocationNullable = Path.GetDirectoryName(EntryAssembly.Location);
if (LocationNullable is null)
{
throw new Exception("The CLR method of Assembly.GetEntryAssembly().Location returned null");
}
string ExecutableLocationPath = LocationNullable;
【问题讨论】:
-
当值实际上为空时,不清楚你想要什么行为。
-
嗯,它们不应该为空,它们是从 CLR 返回的。我不确定它们怎么可能是空的。我只是想让可空到不可空的转换警告消失,而不仅仅是在它们周围放置警告抑制标记。如果其中一个为 null,则会引发异常并关闭程序。
标签: c# c#-8.0 nullable-reference-types