C# 为什么Resharper/Jetbrains[NotNull]注释接口会警告我NullReferenceException?
我正在努力完成我的项目,并用相应的Resharper/Jetbrains注释注释我的所有方法,这样当我不小心试图传递不属于某个地方的东西时,我会得到一些帮助和一些东西 然而,这是我无法理解的 考虑以下几点:C# 为什么Resharper/Jetbrains[NotNull]注释接口会警告我NullReferenceException?,c#,annotations,resharper,C#,Annotations,Resharper,我正在努力完成我的项目,并用相应的Resharper/Jetbrains注释注释我的所有方法,这样当我不小心试图传递不属于某个地方的东西时,我会得到一些帮助和一些东西 然而,这是我无法理解的 考虑以下几点: public interface ITestClass { Task<int?> TestMethod([CanBeNull] int? testInput); } public class TestClass : ITestClass { public asy
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
{
任务测试方法([CanBeNull]int?测试输入);
}
公共类TestClass:ITestClass
{
公共异步任务TestMethod(int?testInput)
{
返回等待任务。FromResult(testInput);
}
}
公共类TestConsumer
{
[非空]
专用只读ITestClass m_测试仪;
[非空]
私有只读测试类m_tester2;
公共TestConsumer([NotNull]ITestClass tester,[NotNull]TestClass tester2)
{
m_测试仪=测试仪;
m_tester2=tester2;
}
公共异步任务TestMethod([NotNull]int?testInput)
{
var test1=等待m_测试仪。测试方法(测试输入);
var test2=等待m_tester2.TestMethod(testInput);
}
}
我重建了它,以显示我现在面临的问题。通常,我正在使用依赖注入,并且我希望在我的控制器(例如,控制器)的构造函数中有某些服务的接口(在这种情况下,让'ITestClass'成为服务'TestClass'的接口)(请参见'TestConsumer')
然而,R#/Jetbrains注释显然不喜欢这样。然而,当我尝试使用该接口的实现时——没有问题
这真的有点烦人。我不想让我的整个代码现在被篡改。显然,这也只是处理wait/async代码时的一个问题,因为如果我省略“wait”这个词,这两种情况都适用,但这不是一个选项
有什么解决办法吗?最后,R#在实现中的接口中可能缺少什么?方法定义就在那里
编辑:
有关更多信息:
我正在Visual Studio Enterprise 2017版本15.6.1中运行Resharper Ultimate 2018.3.1。实现(TestClass.TestMethod)是一个异步方法,它返回任务实例,并且从不返回null。接口方法“ITestClass.TestMethod”的签名不能保证结果不为null(您可以使用只返回null的非异步方法实现它)。所以在“悲观”分析模式下,ReSharper假设“ITestClass.TestMethod”可以返回null。要修复此问题,可以将“NotNull”注释添加到接口的方法中:
public interface ITestClass
{
[NotNull] Task<int?> TestMethod([CanBeNull] int? testInput);
}
公共接口ITestClass
{
[NotNull]任务测试方法([CanBeNull]int?测试输入);
}
我们可以直接发布代码而不是图片吗?这对我来说不太合适(使用R#2016.1.2),所以可能有一个设置将其关闭?将来,您可能希望编辑原始帖子-以免丢失原始帖子中的评论等。@JonathonChase有人已经这么做了。谢谢,在这里工作的人:)很好的解决方案!我的印象是,我必须用返回类型注释方法,例如带有[ItemNotNull]的Task,因此R#会评估返回的Task的内容。[ItemNotNull]在返回Task的方法上告诉ReSharper任务结果的可空性