मैं इंटरफ़ेस IEqualityComparer के GetHashCode विधि की भूमिका को समझने की कोशिश कर रहा हूं।
निम्न उदाहरण MSDN से लिया गया है:
using System;
using System.Collections.Generic;
class Example {
static void Main() {
try {
BoxEqualityComparer boxEqC = new BoxEqualityComparer();
Dictionary<Box, String> boxes = new Dictionary<Box,
string>(boxEqC);
Box redBox = new Box(4, 3, 4);
Box blueBox = new Box(4, 3, 4);
boxes.Add(redBox, "red");
boxes.Add(blueBox, "blue");
Console.WriteLine(redBox.GetHashCode());
Console.WriteLine(blueBox.GetHashCode());
}
catch (ArgumentException argEx) {
Console.WriteLine(argEx.Message);
}
}
}
public class Box {
public Box(int h, int l, int w) {
this.Height = h;
this.Length = l;
this.Width = w;
}
public int Height { get; set; }
public int Length { get; set; }
public int Width { get; set; }
}
class BoxEqualityComparer : IEqualityComparer<Box> {
public bool Equals(Box b1, Box b2) {
if (b1.Height == b2.Height & b1.Length == b2.Length
& b1.Width == b2.Width) {
return true;
}
else {
return false;
}
}
public int GetHashCode(Box bx) {
int hCode = bx.Height ^ bx.Length ^ bx.Width;
return hCode.GetHashCode();
}
}
दो बॉक्स ऑब्जेक्ट्स की तुलना करने के लिए समान पद्धति का कार्यान्वयन पर्याप्त नहीं होना चाहिए? यह वह जगह है जहां हम रूपरेखा को वस्तुओं की तुलना करने के लिए इस्तेमाल किया जाने वाला नियम बताते हैं। GetHashCode की आवश्यकता क्यों है?
धन्यवाद।
लुसियान