1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
public class CompositKey<T, K> : IEquatable<CompositKey<T, K>> where T:IEquatable<T> where K:IEquatable<K>
{
public CompositKey(T key1, K key2)
{
Key1 = key1;
Key2 = key2;
if (Key1 == null || Key2 == null)
throw new ArgumentNullException(Key1 == null ? "Key1" : "Key2");
}
public virtual T Key1 { get; protected set; }
public virtual K Key2 { get; protected set; }
public override int GetHashCode()
{
return (int)(Key1.GetHashCode() + Key2.GetHashCode());
}
#region IEquatable<CompositKey<T,K>> Membres
public bool Equals(CompositKey<T, K> other)
{
if (ReferenceEquals(other,null))
return false;
else
{
bool c1, c2;
if (Key1 == null)
c1 = other.Key1 == null;
else
c1 = Key1.Equals(other.Key1);
if (Key2 == null)
c2 = other.Key2 == null;
else
c2 = Key2.Equals(other.Key2);
return c1 && c2;
}
}
#endregion
public static bool operator ==(CompositKey<T, K> a, CompositKey<T, K> b)
{
if (ReferenceEquals(a, null))
return ReferenceEquals(b, null);
else
return a.Equals(b);
}
public static bool operator !=(CompositKey<T, K> a, CompositKey<T, K> b)
{
if (ReferenceEquals(a, null))
return !ReferenceEquals(b, null);
else
return !a.Equals(b);
}
}
/* ET LE TEST !! */
public Form1()
{
Dictionary<CompositKey<string, string>, string> test
= new Dictionary<CompositKey<string, string>, string>();
test[new CompositKey<string, string>("A", "B")] = "chat";
test[new CompositKey<string, string>("A", "C")] = "chien";
var gh = new CompositKey<string, string>("A", "C");
MessageBox.Show(gh.Equals(new CompositKey<string, string>("A", "C")).ToString());
MessageBox.Show((gh == (new CompositKey<string, string>("A", "C"))).ToString());
MessageBox.Show(test.ContainsKey(new CompositKey<string, string>("A", "B")).ToString());
MessageBox.Show(test.ContainsKey(new CompositKey<string, string>("A", "C")).ToString());
MessageBox.Show(test.ContainsKey(new CompositKey<string, string>("D", "B")).ToString());
MessageBox.Show(test[new CompositKey<string, string>("A", "B")]);
} |
Partager