Compare two System.Enum of type T

后端 未结 2 1576
醉话见心
醉话见心 2021-01-17 23:26

I am pretty close to understand Generics now (I think).
However, just figured that System.Enum is not easy to implement as a generic type. I have this class:

<         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 00:11

    You are trying to perform a reference comparison on a value type (struct), use Equals for equality instead:

    public Button GetButton(TEnum Identifier) {
        var button = _buttons
            .Where(b => EqualityComparer.Default.Equals(b.Identifier, Identifier))
            .FirstOrDefault();
    
        if (button == null)
            Debug.Log("'" + GetType().Name + "' cannot return an unregistered '" + typeof(Button).Name + "' that listens to '" + typeof(TEnum).Name + "." + Identifier.ToString() + "'.");
        return button;
    }
    

    The button.Identifier == Identifier statement cannot be performed, because the == operator does not exist for structs. On a class it would have performed a reference comparison.

    And as @JeppeStigNielsen noted in his answer, to prevent a boxing equality comparison, it is better to use the EqualityComparer.Default.Equals method.

提交回复
热议问题