作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 C# 项目 nullable reference types启用:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<!-- more stuff here -->
</Project>
[*.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;
}
[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;
}
关于c# - 引用不经意的代码时,可空引用类型会静默失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61433521/
我是一名优秀的程序员,十分优秀!