简体   繁体   中英

How to make dictionary extension-methods?

I'm trying to write a Dictionary extension that works independently of the data types of Key/Value. I tried pass it by using the object data type, assuming that it will works with any type.

My code:

 public static class DictionaryExtensionsClass
    {
        public static void AddFormat(this Dictionary< ?? unknow type/*object*/, ??unknow type/*object*/> Dic, ??unknow type/*object*/ Key, string str, params object[] arglist)
        {
            Dic.Add(Key, String.Format(str, arglist));
        }
    }

You just make the method generic:

public static void AddFormat<TKey>(this Dictionary<TKey, string> dictionary,
    TKey key,
    string formatString,
    params object[] argList)
{
    dictionary.Add(key, string.Format(formatString, argList));
}

Note that it's only generic in the key type as the value would have to be string (or potentially object or an interface that string implements, I guess) given that you're going to add a string value to it.

Unfortunately you can't really express the constraint of "only allow value types where string is a valid value" in a generic type constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM