在下面的示例中,有没有办法我可以将空值引用类型转换为非空值引用类型呢?
这将在启用编译器的可空引用标志时使用。
当可为空的引用类型为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;
Run Code Online (Sandbox Code Playgroud)
Jon*_*ase 10
You can use throw expressions with the null coalescing operator.
Assembly EntryAssembly = Assembly.GetEntryAssembly() ?? throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");
Run Code Online (Sandbox Code Playgroud)