在下面的示例中,有没有一种方法可以将空值引用类型转换为非空值引用类型?
这是针对启用编译器的可空引用标志的情况。
当可为空的引用类型为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;
答案 0 :(得分:10)
您可以将throw expressions与null coalescing operator一起使用。
Assembly EntryAssembly = Assembly.GetEntryAssembly() ?? throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");