Byte enum comparison in C#

后端 未结 3 716
梦如初夏
梦如初夏 2021-01-11 12:56

Given this enum

public enum UserStatus : byte
{
    Approved = 1,
    Locked = 2,
    Expire = 3
}

why does this check always return false

3条回答
  •  佛祖请我去吃肉
    2021-01-11 13:41

    The first thing any Equals implementation usually checks is: "is this the right type". And UserStatus is not the same as byte.

    (actually, this only happens because you have boxed the items via your incompatible use of Equals; at the IL level they are indistinguishable until boxed)

    You must compare them as items of the same type. To borrow some code from byte:

    public override bool Equals(object obj)
    {
        return ((obj is byte) && (this == ((byte) obj)));
    }
    

提交回复
热议问题