我正在使用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.
如何修复我的代码以使其可编译?非常感谢。
您的问题是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
返回的字符串。
您可以使用.CodeBase
告诉编译器此处的值不能为null-forgiving operator !
,例如
!
或使用null
和一些默认值
var location = new Uri(assembly.GetName().CodeBase!);
[null-coalescing operator ??
通常被视为警告,似乎您已经在项目设置中启用了此选项