将可空引用类型转换为不可空引用类型,更简洁
Converting a nullable reference type to a non-nullable reference type, less verbosely
在下面的示例中,有没有一种方法可以更简洁地将可空引用类型转换为不可空引用类型?
这适用于启用编译器的可为空引用标志的情况。
当可空引用类型为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;
您可以使用 throw expressions with the null coalescing operator.
Assembly EntryAssembly = Assembly.GetEntryAssembly() ?? throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");
在下面的示例中,有没有一种方法可以更简洁地将可空引用类型转换为不可空引用类型?
这适用于启用编译器的可为空引用标志的情况。
当可空引用类型为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;
您可以使用 throw expressions with the null coalescing operator.
Assembly EntryAssembly = Assembly.GetEntryAssembly() ?? throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");