How to make dictionary extension-methods?

心不动则不痛 提交于 2019-12-03 23:31:47

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!