将可空引用类型转换为非可空引用类型,更简洁地表达

11

在下面的示例中,有没有更简洁的方法将可空引用类型转换为非可空引用类型?

当启用编译器的可空引用标志时,可以使用此方法。

当可空引用类型为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;

1
当值实际上为null时,您想要什么行为并不清楚。 - 500 - Internal Server Error
好的,它们从CLR返回时不应该为null。我不确定它们如何可能为空。我只是想让可空转非空的警告消失,而不是在它们周围放置警告抑制标记。如果其中任何一个为空,它会抛出异常并关闭程序。 - TheColonel26
1个回答

13

您可以使用throw 表达式空值合并运算符

Assembly EntryAssembly = Assembly.GetEntryAssembly() ?? throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接