【问题标题】:Converting a nullable reference type to a non-nullable reference type, less verbosely将可空引用类型转换为不可空引用类型,不那么冗长
【发布时间】: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


【解决方案1】:

您可以将throw expressionsnull coalescing operator 一起使用。

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

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2011-12-04
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2011-03-10
    • 2012-08-01
    相关资源
    最近更新 更多