📜  在C#中获取指定范围的哈希码

📅  最后修改于: 2021-05-29 18:05:05             🧑  作者: Mango

范围结构在C#8.0中引入。它表示具有开始索引和结束索引的范围。您可以在Range结构提供的GetHashCode()方法的帮助下获取指定范围的哈希码。此方法返回指定实例的哈希码。

句法:

public override int GetHashCode();

范例1:

// C# program to illustrate how to find 
// the hash code of the given ranges
// Using GetHashCode() method of Range
// struct
using System;
  
namespace range_example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating range
        // using Range constructor
        var r1 = new Range(2, 4);
  
        // Creating range
        // using Range operator
        Range r2 = 1..10;
  
        // Creating a range
        // using StartAt() method
        var r3 = Range.StartAt(4);
  
        // Get the hash code of the given ranges
        Console.WriteLine("Hash Code of Range_1: " +r1.GetHashCode());
        Console.WriteLine("Hash Code of Range_2: " + r2.GetHashCode());
        Console.WriteLine("Hash Code of Range_3: " + r3.GetHashCode());
    }
}
}

输出:

Hash Code of Range_1: -1254614029
Hash Code of Range_2: 853498667
Hash Code of Range_3: -1528050329

范例2:

// C# program to illustrate how to find
// the hash code of the given ranges
// Using GetHashCode() method of Range struct
using System;
   
namespace range_example {
   
class GFG {
   
    // Main Method
    static void Main(string[] args)
    {
        // Creating and initializing an array
        int[] arr = new int[8] {100, 200, 300, 400,
                               500, 600, 700, 800};
   
        // Creating a range
        // using StartAt() method
        var r = Range.StartAt(3);
        var new_arr = arr[r];
   
        // Displaying the range
        // and the elements
        Console.WriteLine("Range: " + r);
        Console.Write("HashCodes: ");
   
        foreach(var i in new_arr)
            Console.Write($" [{i.GetHashCode()}]");
    }
}
}

输出:

Range: 3..^0
HashCodes:  [400] [500] [600] [700] [800]