使用 GetHashCode 获取 Enum int 值 [英] Using GetHashCode for getting Enum int value

查看:27
本文介绍了使用 GetHashCode 获取 Enum int 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举

public enum INFLOW_SEARCH_ON
{
  ON_ENTITY_HANDLE = 0,         
  ON_LABEL = 1,                 
  ON_NODE_HANDLE = 2            
} // enum INFLOW_SEARCH_ON

我必须使用这个枚举在网格列中进行搜索.

I have to use this enum for searching in a grid column.

获取我正在使用的列索引

To get the column index I am using

  MyEnumVariable.GetHashCode() 

哪个工作正常,或者我应该使用

Which works ok, or should I use

  (short)MyEnumVariable

我对使用 GetHashCode() 有点困惑.使用它有什么问题吗?

I am a bit confused over using GetHashCode(). Is there any problem using that?

推荐答案

使用 GetHashCode() 是不正确的.您应该转换为 int.以你的方式使用它就是要求猛禽(或雷蒙德)来吃掉你.

Using GetHashCode() is incorrect. You should cast to int. Using it the way you do is asking for raptors(or Raymond) to come and eat you.

GetHashCode() 恰好返回枚举的整数值是一个实现细节,可能会在 .net 的未来版本中发生变化.

That GetHashCode() happens to return the integer value of the enum is an implementation detail and may change in future versions of .net.

GetHashCode() 保证如果两个值相等,它们的哈希码也相等.反之则不能保证.

GetHashCode() guarantees that if two values are equal their hash codes are equal too. The other way round is not guaranteed.

我的经验法则是,如果 GetHashCode 返回一个常量值,你的程序应该仍然可以正常工作(但可能会慢得多),因为一个常量 GetHashCode 简单地履行了合约,但具有糟糕的分发特性.

My rule of thumb is that if GetHashCode were to return a constant value your program should still work correctly (but potentially be much slower) since a constant GetHashCode trivially fulfills the contract, but has bad distribution properties.

这篇关于使用 GetHashCode 获取 Enum int 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆