Дубликат ключа журнала Dictionary ArgumentException: какой более производительный?C#

Место общения программистов C#
Ответить
Anonymous
 Дубликат ключа журнала Dictionary ArgumentException: какой более производительный?

Сообщение Anonymous »


Here I add something to a Dictionary:

dictionary.Add(dictionaryKey, value); if dictionaryKey already exists, an ArgumentException will be thrown. Its message is fairly generic:

An item with the same key has already been added.

If my call to dictionary.Add is inside of a loop or a helper function, it can be hard to tell immediately what key has already been added that is throwing this exception. I would like to know this as easily and as soon as possible.

There are a few options.

1)

if (dictionary.ContainsKey(dictionaryKey)) { throw new ArgumentException($"An item with the same key ({dictionaryKey}) has already been added."); } dictionary.Add(dictionaryKey, value);
try { dictionary.Add(dictionaryKey, value); } catch (ArgumentException argumentException) { throw new ArgumentException($"An item with the same key ({dictionaryKey}) has already been added."); }
  • Some other way
I know setting up a try/catch block takes a performance hit, but it seems running dictionary.ContainsKey(dictionaryKey) would mean an additional lookup each time too. Which of these options is most performant?


Источник: https://stackoverflow.com/questions/448 ... performant
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»