gpt4 book ai didi

c# - 为什么 Resharper/Jetbrains [NotNull] 注释接口(interface)会警告我 nullreferenceexceptions?

转载 作者:行者123 更新时间:2023-11-30 21:30:37 25 4
gpt4 key购买 nike

我正在尝试完成我的项目并使用相应的 Resharper/Jetbrains 注释来注释我的所有方法,这样当我不小心尝试传递不属于某处的东西时,我会得到一点帮助和一些打击。

然而,这是我无法理解的事情。

考虑以下几点:

public interface ITestClass
{
Task<int?> TestMethod([CanBeNull] int? testInput);
}

public class TestClass : ITestClass
{
public async Task<int?> TestMethod(int? testInput)
{
return await Task.FromResult(testInput);
}
}

public class TestConsumer
{
[NotNull]
private readonly ITestClass m_tester;

[NotNull]
private readonly TestClass m_tester2;

public TestConsumer([NotNull] ITestClass tester, [NotNull] TestClass tester2)
{
m_tester = tester;
m_tester2 = tester2;
}

public async Task TestMethod([NotNull] int? testInput)
{
var test1 = await m_tester.TestMethod(testInput);
var test2 = await m_tester2.TestMethod(testInput);
}
}

![enter image description here

我重建它是为了展示我现在面临的问题。通常,我正在使用依赖注入(inject),我希望在我的构造函数中使用某些服务的接口(interface)(在这种情况下,让“ITestClass”成为服务“TestClass”的接口(interface))。 Controller (参见“TestConsumer”)。

然而,R#/Jetbrains Annotations 显然不喜欢这样。但是,当我尝试使用该接口(interface)的实现时 - 没问题。

这确实有点烦人。我不想让我的整个代码现在摆动。显然,这也只是处理 await/async 代码时的一个问题,因为如果我省略“await”,这对这两种情况都有效,但这不是一个选项。

有什么解决办法吗?最后,R# 在其实现中所具有的接口(interface)中可能缺少什么?方法定义在那里。

编辑:

更多信息:

我在 Visual Studio Enterprise 2017 版本 15.6.1 中运行 Resharper Ultimate 2018.3.1。

最佳答案

实现 (TestClass.TestMethod) 是一种异步方法,它返回 Task 的实例并且从不返回 null。接口(interface)方法“ITestClass.TestMethod”的签名不保证结果不为空(您可以使用仅返回空的非异步方法实现它)。因此,在“悲观”分析模式下,ReSharper 假定“ITestClass.TestMethod”可以返回 null。要修复它,您可以在接口(interface)的方法中添加“NotNull”注释:

public interface ITestClass
{
[NotNull] Task<int?> TestMethod([CanBeNull] int? testInput);
}

关于c# - 为什么 Resharper/Jetbrains [NotNull] 注释接口(interface)会警告我 nullreferenceexceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100235/

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