Enum Boxing and Equality

后端 未结 2 612
眼角桃花
眼角桃花 2021-02-07 09:59

Why does this return False

    public enum Directions { Up, Down, Left, Right }

    static void Main(string[] args)
    {
        bool matches = IsOneOf(Directi         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 10:34

    Enum does not implement a == equality operator but it does override the Equals method.

    Since it does not implement ==, the system performs a reference equality check. Note that System.Enum is a class not a structure. Hence, values such as Directions.Left are boxed. In this particular case, the boxed objects end up being separate objects, hence they fail a reference equality test.

    The compiler understands == for concrete Enum types (such as Directions), but the compiler does not do this special processing against the System.Enum type.

提交回复
热议问题