문제

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