C#中Dictionary,如果键为对象时,怎么比较!

浑沌滴年代 2011-12-10 05:30:06
当字典中的键为对象时,直接用ContainsKey不可以,当向字典中增加的时候,有同样的对象但还是可以加进去,是不是要重写什么东西???具体如何实现!!!???
...全文
584 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
浑沌滴年代 2011-12-12
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 net_lover 的回复:]

对象按地址引用的,要进行比较,你需要重写 Equals
可参考
http://blog.csdn.net/aladdinty/article/details/3400837
[/Quote]

if (dic.ContainsKey(_bsMod))//如果集合中包含此对象,直接返回Table

如果我要像这样写,该怎么实现。。。。。
浑沌滴年代 2011-12-12
  • 打赏
  • 举报
回复
还是自己想出来了。。。结帐
bustersword 2011-12-11
  • 打赏
  • 举报
回复
/// <summary>
/// A result is a search result which contains a post and its ranking.
/// </summary>
internal class Result : IComparable<Result>
{
#region Constants and Fields

/// <summary>
/// The post of the result.
/// </summary>
internal IPublishable Item;

/// <summary>
/// The rank of the post based on the search term. The higher the rank, the higher the post is in the result set.
/// </summary>
internal int Rank;

#endregion

#region Public Methods

/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return this.Item.Id.GetHashCode();
}

#endregion

#region Implemented Interfaces

#region IComparable<Result>

/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">
/// An object to compare with this object.
/// </param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value
/// has the following meanings: Value Meaning Less than zero This object is less than the other parameter.Zero
/// This object is equal to other. Greater than zero This object is greater than other.
/// </returns>
public int CompareTo(Result other)
{
return other.Rank.CompareTo(this.Rank);
}

#endregion

#endregion
}

看看
阿非 2011-12-11
  • 打赏
  • 举报
回复
需要重写 Equals 和 GetHashCode 两个方法
ycg_893 2011-12-10
  • 打赏
  • 举报
回复
如果是同一对象可直接Equals
但如果是不同的对象,但值一样与必须重写 Equals
孟子E章 2011-12-10
  • 打赏
  • 举报
回复
对象按地址引用的,要进行比较,你需要重写 Equals
可参考
http://blog.csdn.net/aladdinty/article/details/3400837

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧