سؤال

I have written an extension method to help with collecting crash data during error reporting. This method is designed to ensure that a key is always unique. If you have a few try/catch blocks, sometimes data can get duplicated. I'm going for reasonably easy here, not super-best practices.

The problem: changing the key if it isn't unique. When I try the below, method, I get "cannot convert from 'string' to 'TKey'". Any ideas?

    public static void AddUnique<TKey, TValue>(this System.Collections.IDictionary dictionary, TKey key, TValue value)
    {
        if(dictionary[key] != null)
        {
            var newKey = key.ToString() + "-";
            AddUnique<TKey, TValue>(dictionary, newKey, value);
        }               

        ...
    }
هل كانت مفيدة؟

المحلول

If you know your keys will always be strings, then remove the TKey generic parameter from the method signature, and just use string in its place. Alternatively, you may want to keep both generic parameters, but change the recursive call to AddUnique<string, TValue>().

نصائح أخرى

You cannot concatenate a string to every possible key out there. You have to solution to this problem:

  • use only strings as keys
  • use something that is unique always e.g. URL or GUID*

It's not really unique, but the probability of a collision is near 0, especially on a single machine. More info on the subject.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top