加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 比较两个类型为T的System.Enum

发布时间:2020-12-15 17:49:02 所属栏目:百科 来源:网络整理
导读:我现在非常接近了解Generics(我认为). 但是,只是认为System.Enum不容易实现为泛型类型. 我有这门课: public class ButtonTEnum where TEnum : struct,IConvertible,IComparable,IFormattable { public TEnum Identifier { get; private set; //Set in the c
我现在非常接近了解Generics(我认为).
但是,只是认为System.Enum不容易实现为泛型类型.
我有这门课:
public class Button<TEnum> where TEnum : struct,IConvertible,IComparable,IFormattable {
   public TEnum Identifier {
        get;
        private set; //Set in the ctor
    }
}

public abstract class AbstractInputDevice<TEnum> where TEnum : struct,IFormattable {

   private List<Button<TEnum>> _buttons = new List<Button<TEnum>>();

   public Button<TEnum> GetButton(TEnum Identifier){
        foreach(Button<TEnum> button in _buttons){
            if(button.Identifier == Identifier) //<- compiler throws
                return button;
        }
        Debug.Log("'" + GetType().Name + "' cannot return an <b>unregistered</b> '" + typeof(Button<TEnum>).Name + "' that listens to '" + typeof(TEnum).Name + "." + Identifier.ToString() + "'.");
        return null;
    }
}

InputDevice可能看起来像这样:

public class Keyboard : AbstractInputDevice<KeyCode> {
    private void Useless(){
        Button<KeyCode> = GetButton(KeyCode.A);
    }
}

编译器在这里抛出一个编译错误:

if(button.Identifier == Identifier) //In AbstractInputDevice above

我相信我无法比较这两个TEnums,因为它们实际上并不是Enums.
因此没有比较方法可用.

我用过这个资源:
Create Generic method constraining T to an Enum

我感谢任何更好的解决方案或修复.
(但我想将Enum条目作为GetButton(EnumEntry)的参数保留)

解决方法

而不是不可能的
button.Identifier == Identifier

你应该使用

EqualityComparer<TEnum>.Default.Equals(button.Identifier,Identifier)

这样可以避免将值装入对象框(或IComparable框).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读