gpt4 book ai didi

c# - KeyedCollection 是不是只有Key 判断里面的item 是否相等的意思?

转载 作者:行者123 更新时间:2023-11-30 20:58:37 25 4
gpt4 key购买 nike

我认为这是我们遇到的一个常见问题。

class Person
{
public string place;
public string name;

public Person(string place, string name)
{
this.place = place;
this.name = name;
}

public bool Equals(Person other)
{
if (ReferenceEquals(null, other))
return false;

return name == other.name;
}

public override bool Equals(object obj)
{
return Equals(obj as Person);
}

public override int GetHashCode()
{
return name.GetHashCode();
}

public override string ToString()
{
return place + " - " + name;
}
}

假设我有这门课。我可以实现 KeyedCollection像这样:

class Collection : KeyedCollection<string, Person>
{
protected override string GetKeyForItem(Person item)
{
return item.place;
}
}

这里的情况是默认Equals基于namePerson但就我而言,我正在创建自定义 collection那将只有一个 Personplace .换句话说 place将在 collection 中是唯一的.

Person p1 = new Person("Paris", "Paul");
Person p2 = new Person("Dubai", "Ali");

var collection = new Collection { p1, p2 };
var p3 = new Person("Paris", "Jean");
if (!collection.Contains(p3))
collection.Add(p3); // explosion

我明白这个问题。 Contains(Person)过载是 Collection<T>.Contains(T) 的过载在 Add(Person) 时进行基于值的线性搜索确实将值添加到内部字典,这可能导致重复键异常。在这里, had equality 是基于 place ,这个问题就不会存在。

我可以想出一个解决方法:

class Collection : KeyedCollection<string, Person>
{
protected override string GetKeyForItem(Person item)
{
return item.place;
}

new public bool Contains(Person item)
{
return this.Contains(GetKeyForItem(item));
}
}

但这又意味着如果我做一个一般的

var p3 = new Person("Paris", "Jean");
bool b = collection.Contains(p3); //true

返回 true , 但实际上 Jean collection 中不存在然而。所以我的问题是,KeyedCollection<K, T>只有在 Equals 时才有意义仅基于 K T 的一部分?我的问题在语义方面很少。 我不是在寻求解决方案,只是知道是否对 KeyedCollection有道理吗?我在文档中找不到与此主题相关的任何内容。

更新:

我已经找到这里提到的确切问题 http://bytes.com/topic/net/answers/633980-framework-bug-keyedcollection-t

提问者向 MS 提交错误报告的位置。引用他的话(日期为 2007 年 4 月 18 日):

I submitted this as a bug to Microsoft, and they have verified it andaccepted it. It's Issue ID 271542, and can be tracked here:

"We have reproduced this bug on WinXP pro SP2 and VSTS2005 SP1, andwe are sending this bug to the appropriate group within the VisualStudio Product Team for triage and resolution."

虽然我不认为这是一个错误,但这确实是一个烦恼。但只是想知道 MS 最初是如何将此视为错误的(预计,现在无法找到该页面)。 Imo,它只是考虑不周的继承模型。

最佳答案

询问集合似乎有两件事是有意义的:

  • 是否包含住在巴黎的,以及

  • 它是否包含一个住在巴黎的人

KeyedCollection<TKey, TItem> Class恰好提供了两种方法来提出这些问题:

住在巴黎的名叫让的人不是同一个人名叫保罗,住在巴黎 ( Person.Equals )。但是如果有一个人住在巴黎,那么根据你的规则,不可能有另一个 住在巴黎的人

所以基本上你必须在添加新人之前向集合询问正确的问题:

if (!collection.Contains(p3.place))
collection.Add(p3);

为方便起见,您可以在类中添加一个 TryAdd 方法,如果成功添加了 人,或者如果集合中已经有一个 人住在同一个地方:

public bool TryAdd(Person person)
{
if (Contains(GetKeyForItem(person)))
return false;
Add(person);
return true;
}

关于c# - KeyedCollection 是不是只有Key 判断里面的item 是否相等的意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15983720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com