سؤال

I'd like to create an extension method to the IDictionary collection Exception.Data that allows me to add an item to the dictionary without having to ensure the key is unique.

I can't get the extension method to show up.

    public static void AddUnique<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
    {

    }

You would use this like

exception.Data.AddUnique("key", value);

What am I doing wrong? Is this even possible?

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

المحلول 2

The type in the extension method must exactly match the type of Exception.Data, which is System.Collections.IDictionary.

System.Collections.Generic.IDictionary <> System.Collections.IDictionary

System.Collections.IDictionary does not have type parameters, so the proper code would be

    public static void AddUnique<TKey, TValue>(this System.Collections.IDictionary dictionary, TKey key, TValue value)
    {

    }

نصائح أخرى

Where are you declaring this? Ideally, you should have a static class to contain this method. Then, if it's in a different namespace, you need to make sure that you have a using statement for that namespace.

namespace MyNamespace
{
    public static class MyExtensions
    {

        public static void AddUnique<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, 
                                                   TKey key, 
                                                   TValue value)
        {
            // implementation code
        }
    }
}

and later...

using MyNamespace;  // if required

//  in a method
exception.Data.AddUnique(key, value);

Note: You also had key as "key", which is a string literal. May not work if your TKey is not a string.

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