本文介绍了可能会返回default(T)的异步泛型方法的正确的可为空的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将具有可为空的引用类型的代码库转换为C#8.在这个问题中,我遇到了一种类似于的方法,但是异步.

I am converting a codebase to C#8 with nullable reference types. I came across the a method similar to the one in this question but async.

public async Task<T> GetAsync<T>()
{
    // sometimes returns default(T); => warning CS8603 Possible null reference return
}

T可以是任何类型,包括可为空的引用类型或可为空的值类型.

T may be any type, including nullable reference types or nullable value types.

需要明确的是,我了解为什么此方法会触发警告.我想知道什么注释可以用来解决它.

To be clear, I understand WHY this method triggers a warning. What I'd like to know is what annotations can be used to resolve it.

  • 我知道我可以使用#nullable disable或default(T)!,但是我一直希望没有锤子".
  • 我知道我不能使用[return: MaybNull],因为这将适用于Task本身,而不是T.
  • I know I can use #nullable disable or default(T)!, but I was hoping for something that's less of a "hammer".
  • I know I can't use [return: MaybNull] because that would apply to the Task itself, not the T.

我是否可以使用其他属性/注释使编译器满意,或者default(T)!是我唯一的选择?

Is there any other attribute/annotation I can apply to make the compiler happy, or is default(T)! my only option?

推荐答案

通过搜索和进行更多的研究,看来在这种情况下抑制警告的首选方法是在default(T)上使用!运算符.

From searching around and doing more research, it appears that the preferred way to suppress the warning in this context is to use the ! operator on default(T).

这篇关于可能会返回default(T)的异步泛型方法的正确的可为空的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 12:46