How to make dictionary extension-methods?

2019-04-04 02:59发布

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));
        }
    }

1条回答
萌系小妹纸
2楼-- · 2019-04-04 03:25

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.

查看更多
登录 后发表回答