如何将可为空的对象引用分配给不可为空的变量?

问题描述 投票:0回答:2

我正在使用VS2019,并在项目设置中启用了可为空的检查语义。我正在尝试使用以下程序集获取可执行文件的路径:

        var assembly = Assembly.GetEntryAssembly();
        if (assembly == null)
        {
            throw new Exception("cannot find exe assembly");
        }
        var location = new Uri(assembly.GetName().CodeBase);//doesn't compile.

它说“ assembly”是[Assembly?]类型,而Uri ctor需要一个字符串,则编译错误是:

error CS8602: Dereference of a possibly null reference.

如何修复我的代码以使其可编译?非常感谢。

c# compilation reference .net-assembly nullable
2个回答
4
投票

您的问题是AssemblyName.CodeBase可为空:类型为AssemblyName.CodeBase

您需要添加额外的代码来处理string?.CodeBase的情况(或用null抑制它,例如:

!

var codeBase = Assembly.GetEntryAssembly()?.GetName().CodeBase;
if (codeBase == null)
{
    throw new Exception("cannot find exe code base");
}
var location = new Uri(codeBase);

在这种情况下,您得到的实际警告与var location = new Uri(assembly.GetName().CodeBase!); 无关,它是:

警告CS8604:'Uri.Uri(string uriString)'中的参数'uriString'可能为空引用参数。

assembly(展开右下角的“警告”窗格)。这告诉您问题出在将字符串传递到Source构造函数中,即从Uri返回的字符串。


3
投票

您可以使用.CodeBase告诉编译器此处的值不能为null-forgiving operator !,例如

!

或使用null和一些默认值

var location = new Uri(assembly.GetName().CodeBase!);

[null-coalescing operator ??通常被视为警告,似乎您已经在项目设置中启用了此选项

© www.soinside.com 2019 - 2024. All rights reserved.