gpt4 book ai didi

c# - 将可空引用类型转换为不可空引用类型,更简洁

转载 作者:太空狗 更新时间:2023-10-29 20:09:17 25 4
gpt4 key购买 nike

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

这适用于启用编译器的可为空引用标志的情况。

当可空引用类型为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 expressionsnull coalescing operator .

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

关于c# - 将可空引用类型转换为不可空引用类型,更简洁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com