简体   繁体   English

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

[英]How to assign a nullable object reference to a non-nullable variable?

I am using VS2019 and has enabled nullable check semantics in project setting.我正在使用 VS2019 并在项目设置中启用了可为空检查语义。 I am trying to get the executable's path using assembly as below:我正在尝试使用程序集获取可执行文件的路径,如下所示:

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

It says, "assembly" is a [Assembly?] type, while the Uri ctor requires a string, compilation error is:它说,“assembly”是一个 [Assembly?] 类型,而 Uri ctor 需要一个字符串,编译错误是:

error CS8602: Dereference of a possibly null reference.

How to fix my code to make it compile?如何修复我的代码以使其编译? Thanks a lot.非常感谢。

Your problem is that AssemblyName.CodeBase is nullable: it's of type string?您的问题是AssemblyName.CodeBase为空:它是string?类型string? . .

You need to add extra code to handle the case where .CodeBase is null (or suppress it with ! ), eg:您需要添加额外的代码来处理.CodeBasenull的情况(或用!抑制它),例如:

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

or或者

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

The actual warning you get in this case is nothing to do with assembly , it's:在这种情况下您得到的实际警告与assembly无关,它是:

warning CS8604: Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)'.警告 CS8604:“Uri.Uri(string uriString)”中参数“uriString”的可能为空引用参数。

Source (expand the "Warnings" pane on the lower right). 来源(展开右下角的“警告”窗格)。 This tells you that the problem is with the string being passed into the Uri constructor, ie the string returned from .CodeBase .这告诉您问题在于传递给Uri构造函数的字符串,即从.CodeBase返回的字符串。

You can use null-forgiving operator !您可以使用null-forgiving 运算符! to tell the compiler that CodeBase can't be null告诉编译器CodeBase不能为null

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

or use a null-coalescing operator ??或使用空合并运算符?? with some default value有一些默认值

var location = new Uri(assembly.GetName().CodeBase ?? string.Empty);

The error错误

CS8604: Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)' CS8604:“Uri.Uri(string uriString)”中参数“uriString”的可能为空引用参数

usually treated as warning, it seems that you've enabled this option in project settings通常被视为警告,您似乎在项目设置中启用了此选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM