简体   繁体   English

如何为布尔实现GetHashCode?

[英]How is GetHashCode Implemented for Booleans?

我想知道它们如何从C#/。NET中的布尔类型生成哈希码?

You can see the actual source code for .NET here , the implmentation for GetHashCode() for a bool is 您可以在此处查看.NET的实际源代码,对bool的GetHashCode()实现是

  private bool m_value;

  internal const int True = 1; 
  internal const int False = 0; 

  public override int GetHashCode() {
      return (m_value)?True:False;
  }

(And yes, it is weird that System.Boolean contains a bool as a member variable, when the class is compiled the CLR treats the "primitive" types Boolean , Byte , SByte , Int16 , UInt16 , Int32 , UInt32 , Int64 , UInt64 , IntPtr , UIntPtr , Char , Double , and Single special so they can do stuff like that) (是的,奇怪的是System.Boolean包含bool作为成员变量,在编译类时,CLR将“原始”类型视为BooleanByteSByteInt16UInt16Int32UInt32Int64UInt64IntPtrUIntPtrCharDoubleSingle特殊,因此它们可以执行类似的操作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM