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

C# 如何将可为null的对象引用分配给不可为null的变量?,c#,.net-assembly,c#-8.0,nullable-reference-types,C#,.net Assembly,C# 8.0,Nullable Reference Types,我正在使用VS2019,并在项目设置中启用了可空检查语义。我正在尝试使用以下程序集获取可执行文件的路径: var assembly = Assembly.GetEntryAssembly(); if (assembly == null) { throw new Exception("cannot find exe assembly"); } var location = new Uri(ass

我正在使用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构造函数需要字符串,编译错误是:

error CS8602: Dereference of a possibly null reference.
如何修复代码以使其编译? 非常感谢。

您的问题是它可以为null:它的类型是
string?

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


在这种情况下,您得到的实际警告与装配无关,它是:

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

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

返回的字符串,您可以使用该字符串告诉编译器
CodeBase
不能为
null

var location=newURI(assembly.GetName().CodeBase!);
或者使用带有某个默认值的

var location=newURI(assembly.GetName().CodeBase??string.Empty);
错误

CS8604:中参数“uriString”的可能空引用参数 'Uri.Uri(字符串uriString)'


通常被视为警告,您似乎在项目设置中启用了此选项

这是8中最好的操作符之一,非常好的解决方案。
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!);