gpt4 book ai didi

c# - 引用不经意的代码时,可空引用类型会静默失败吗?

转载 作者:行者123 更新时间:2023-12-03 19:13:28 25 4
gpt4 key购买 nike

我有一个 C# 项目 nullable reference types启用:

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<!-- more stuff here -->
</Project>

我在我的 .editorconfig 中设置了几个警告来成为错误:
[*.cs]

# CS8600: Converting null literal or possible null value to non-nullable type.
dotnet_diagnostic.CS8600.severity = error

# CS8603: Possible null reference return.
dotnet_diagnostic.CS8603.severity = error


在我的项目中,我有一个类,以及以下 不会编译 ,这是完美的:
public class NullableCompilerChecking
{
public string WontCompile(string? input)
=> input; // error: "possible null reference return"
}

现在的问题。我的项目引用了另一个名为“库”的项目。图书馆是空的。在图书馆,我有以下几点:
  public static class Strings
{
public static string Null => null;
}

问题是当我从我的库中引用 Strings 类时,我失去了美妙的空检查。例如,以下在运行时编译并抛出:
    [Test]
public void SomeTest()
{
var myString = Strings.Null;
var myIndex = myString.IndexOf("a");
}

我想要的是图书馆的 string默认情况下,以 string? 的形式出现可识别空值的代码而不是 string .我可以这样做吗?

最佳答案

据我所知,如果你想对不支持它的库进行新的空检查,你必须创建一个 wrapper在它周围,具有适当的空意识。例如:

public static class Strings
{
public static string Null => null;
}

// In your code you will use only the wrapper
public static class StringsWrapper
{
public static string? Null => Strings.Null;
}

如果您正在使用 ReSharper,另一个懒惰的选择是打开 pessimistic nullability analisys ,它会在您使用可能为空的值的任何地方为您提供警告/错误。

关于c# - 引用不经意的代码时,可空引用类型会静默失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61433521/

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