Ste*_*e B 4 c# variables c#-4.0
我有一个程序,必须使用复合键管理对象.这个关键,简单就是几个字符串.
我有以下代码:
public struct MyKey
{
public string Part1 { get; set;} // always set
public string Part2 { get; set;} // can be null
public MyKey(string part1, string part2) : this()
{
this.Part1 = part1;
this.Part2 = part2;
}
}
Run Code Online (Sandbox Code Playgroud)
这对于存储我的值是可以的.
现在我希望能够:
我猜测了很多事情(覆盖等于运算符,重写GetHashCode和Equals方法,实现IComparable等),但我不确定实现目标的必要步骤是什么,以及什么会导致开销.
thx提前
使用.NET 4.0 Tuple
,它具有正确的Equals()
并GetHashCode()
基于组件值.我之前使用过Tuple,或者如果它们是字符串键,你总是可以用分隔符连接,但是如果你真的想把这个类作为你的键,你需要一个合适的Equals()和GetHashCode(),所以在这种情况下YourType实现IEqualityComparer<YourType>
.
ps这是一个覆盖GetHashCode()的好例子,如果你想手动而不是元组...
重写System.Object.GetHashCode的最佳算法是什么?
归档时间: |
|
查看次数: |
238 次 |
最近记录: |