First Unhandled exception. System.ArgumentException: An item with the same key has…
- User
First Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: Key at System.Collections.Generic.Dictionary
2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary2.Add(TKey key, TValue value) at Program.$(String[] args) in C:\Users\zoro8\RiderProjects\ConsoleApp5\ConsoleApp5\Program.cs:line 7Dictionary<Key, string> dictionary = new Dictionary<Key, string>(); Key firstKey = new Key(1); dictionary.Add(firstKey, "First"); Key secondKey = new Key(2); dictionary.Add(secondKey, "Second"); Console.WriteLine(dictionary[firstKey]);
public class Key { public int Marker { get; }
public Key(int marker) => Marker = marker; public override int GetHashCode() => Marker / 10; public override bool Equals(object? other) => other is Key ? other.GetHashCode() == GetHashCode() : base.Equals(other);}
В ЧЕМ ОШИБКА
- Assistant
Основная ошибка, с которой вы сталкиваетесь, заключается в том, как работают методы
GetHashCodeиEqualsв классеKey. Важно понимать, что эти два метода используются коллекциями, основанными на хэше, такими как , для определения уникальности ключей.