IEquatable 实现中可能存在的 null 引用

Possible null reference in IEquatable implementation

提问人:nop 提问时间:6/9/2022 更新时间:6/9/2022 访问量:186

问:

我正在尝试了解如何在下面的 IEquatable 实现中删除可能的空引用。

return other != null && _guid == other._guid;'bool SubscriptionToken.operator !=(SubscriptionToken left, SubscriptionToken right)' 中参数“left”的可能空引用参数

public class SubscriptionToken : IEquatable<SubscriptionToken>
{
    public static readonly SubscriptionToken Empty = new(Guid.Empty);

    private readonly Guid _guid;

    private SubscriptionToken(Guid guid)
    {
        _guid = guid;
    }

    private SubscriptionToken()
    {
    }

    public Guid Value => _guid;

    public bool Equals(SubscriptionToken? other)
    {
        return other != null && _guid == other._guid; // Possible null reference
    }

    public bool IsValid()
    {
        return _guid != Guid.Empty;
    }

    public static SubscriptionToken New()
    {
        return new SubscriptionToken(Guid.NewGuid());
    }

    public override bool Equals(object? other)
    {
        return other is SubscriptionToken token && Equals(token);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(_guid);
    }

    public override string ToString()
    {
        return _guid.ToString("N");
    }

    public static bool operator ==(SubscriptionToken left, SubscriptionToken right)
    {
        return EqualityComparer<SubscriptionToken>.Default.Equals(left, right);
    }

    public static bool operator !=(SubscriptionToken left, SubscriptionToken right)
    {
        return !(left == right);
    }
}
C# .NET 可等式

评论

0赞 Sweeper 6/9/2022
查看 stackoverflow.com/questions/73713/...
0赞 nop 6/9/2022
@Sweeper这对我有什么帮助?
0赞 Sweeper 6/9/2022
您是否意识到正在呼叫超载的接线员?other != null
0赞 nop 6/9/2022
@Sweeper,是的,它基本上要求它operator ==(SubscriptionToken? left, SubscriptionToken? right)

答:

1赞 JonasH 6/9/2022 #1

你的 equals 方法可能看起来像这样:

        public bool Equals(SubscriptionToken other)
        {
            if (ReferenceEquals(null, other)) return false;
            return _guid.Equals(other._guid);
        }

这应该可以避免任何空引用异常。

评论

0赞 nop 6/9/2022
public bool Equals(SubscriptionToken? other) { return other is not null && _guid.Equals(other._guid); } 时,IDE 已更正为该模式ReferenceEqualsis not null
1赞 JonasH 6/9/2022
@nop这很好。我没有运行最新的 c# 版本。