/
aprogrammer
/
dotnet-docs
Обзор
Документация
Войти
/
aprogrammer
/
dotnet-docs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
docs/fundamentals/runtime-libraries/snippets/System/Object/GetHashCode/csharp/shift1.cs
72 строки
2 KB
Genevieve Warren
Move member remarks (#39270)
30 янв 2024, 00:43
Не верифицирован
30 янв 2024, 00:43
6c88824
Код
Авторство
О чём код?
// <Snippet5> using System; public struct Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public override bool Equals(Object obj) { if (!(obj is Point)) return false; Point p = (Point) obj; return x == p.x & y == p.y; } public override int GetHashCode() { return ShiftAndWrap(x.GetHashCode(), 2) ^ y.GetHashCode(); } private int ShiftAndWrap(int value, int positions) { positions = positions & 0x1F; // Save the existing bit pattern, but interpret it as an unsigned integer. uint number = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0); // Preserve the bits to be discarded. uint wrapped = number >> (32 - positions); // Shift and wrap the discarded bits. return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) | wrapped), 0); } } public class Example2 { public static void Main() { Point pt = new Point(5, 8); Console.WriteLine(pt.GetHashCode()); pt = new Point(8, 5); Console.WriteLine(pt.GetHashCode()); } } // The example displays the following output: // 28 // 37 // </Snippet5> public class Utility { // <Snippet4> public int ShiftAndWrap(int value, int positions) { positions = positions & 0x1F; // Save the existing bit pattern, but interpret it as an unsigned integer. uint number = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0); // Preserve the bits to be discarded. uint wrapped = number >> (32 - positions); // Shift and wrap the discarded bits. return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) | wrapped), 0); } // </Snippet4> }