【问题标题】:Why do Resharper / Jetbrains [NotNull] annotated interfaces warn me of nullreferenceexceptions?为什么 Resharper / Jetbrains [NotNull] 带注释的接口会警告我 nullreferenceexceptions?
【发布时间】:2019-06-03 15:26:46
【问题描述】:

我正在尝试通过我的项目并使用相应的 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);
    }
}

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

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

这真的有点烦人。我现在不想让我的整个代码摇摆不定。显然,这也只是处理等待/异步代码时的一个问题,因为如果我省略了“等待”,这两种情况都适用,但这不是一个选项。

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

编辑:

更多信息:

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

【问题讨论】:

  • 我们能不能直接贴出代码而不是图片?
  • 这不适合我(使用 R# 2016.1.2)所以也许有一个设置可以关闭它?
  • 将来,您可能希望编辑原始帖子 - 以免丢失原始帖子中的 cmets 等。
  • @JonathonChase 有人已经这么好心了。谢谢,谁在这里工作:)

标签: c# annotations resharper


【解决方案1】:

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

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

【讨论】:

  • 很好的解决方案!我的印象是我必须用返回类型注释方法,例如Task 带有 [ItemNotNull],因此 R# 会评估返回的 Task 的内容。
  • [ItemNotNull] 在返回 Task 的方法上告诉 ReSharper 任务结果的可空性
猜你喜欢
  • 2015-09-20
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多