【问题标题】:MemberNotNullWhenAttribute ignored for async method异步方法忽略 MemberNotNullWhenAttribute
【发布时间】:2022-11-11 10:10:00
【问题描述】:

我有类似于以下的代码。

public List<string>? Data { get; set; }

[MemberNotNullWhen(true, nameof(Data))]
public bool Read()
{
    Data = ReadData();
    return Data != null;
}

MemberNotNullWhenAttribute 表示当方法返回 true 时,Data 不为空。这可以防止在使用 Data 而不显式测试它是否为 null 时出现警告。

这很好用。但现在我想添加此方法的async 版本。

[MemberNotNullWhen(true, nameof(Data))]
public async bool ReadAsync()
{
    Data = await ReadDataAsync();
    return Data != null;
}

这编译得很好并且没有警告。但是MemberNotNullWhenAttribute 完全被忽略了。在此方法返回 true 后使用 Data 仍然会给出可能为 null 的警告。

有没有人想出如何在异步方法中指示成员不为空?我正在写一个图书馆,这种东西很重要。

【问题讨论】:

    标签: c# .net .net-core nullable-reference-types


    【解决方案1】:

    异步方法返回Task&lt;T&gt;,在本例中为Task&lt;bool&gt;。 MemberNotNullWhen 不能处理异步的东西,因为等待 Task 是可选的(在 95% 的情况下你会等待)。

    考虑以下代码

    async Task M()
    {
       Task t = ReadAsync();
       string trim = Data.Capacity; // NullReferenceException. Field was still null because the task was not yet completed
       await t;
    }
    

    这涉及用于分析的更复杂的代码流。 csharp-lang repo 中存在未解决的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-06
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多