指示 ReSharper 当其他属性为“true”时,某个字段不为空

问题描述 投票:0回答:1

我有一个类,我使用像

Exists
这样的属性,当字段
true
不是
_value
时返回
null

此字段稍后用于从中创建

StreamReader
。当我使用它时,
ReSharper
警告我它可能是
null
,但由于我之前用
if(Exists)
阻止了它,所以不会。

我用评论禁用了警告,但我想知道是否有更干净的方法或一些注释或其他技巧来使

ReSharper
明白在
_value
时使用
Exists == true
是安全的?

internal class User
{
    private readonly string _value;

    internal User([NotNull] string name, [CanBeNull] string value)
    {
        _value = value;
    }

    public bool Exists => !(_value is null);

    public async Task CopyToAsync(Stream stream)
    {
        if (Exists)
        {
            // ReSharper disable once AssignNullToNotNullAttribute - '_value' won't be null here
            using (var valueStream = _value.ToStreamReader()) 
            {
                await valueStream.BaseStream.CopyToAsync(stream);
            }
        }
    }   
}
c# resharper
1个回答
0
投票

这是我自己遇到的一个令人沮丧的问题。我不确定您是否找到了有效的 Resharper 注释,但我想添加有关消除 Visual Studio 分析器中的等效警告的信息。我本来希望 Resharper 也会尊重它,但不幸的是,我的经验是它不会。

这是 String.IsNullOrEmpty() 的内部使用方式。

bool IsNullOrEmpty([NotNullWhen(false)] string? value)

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis

© www.soinside.com 2019 - 2024. All rights reserved.