简体   繁体   English

如何制作字典扩展方法?

[英]How to make dictionary extension-methods?

I'm trying to write a Dictionary extension that works independently of the data types of Key/Value.我正在尝试编写一个独立于键/值数据类型工作的Dictionary扩展。 I tried pass it by using the object data type, assuming that it will works with any type.我尝试使用object数据类型传递它,假设它适用于任何类型。

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.请注意,它仅在类型中是通用的,因为如果您要向其添加字符串值,则该值必须string (或者可能是objectstring实现的接口,我猜)。

Unfortunately you can't really express the constraint of "only allow value types where string is a valid value" in a generic type constraint.不幸的是,您无法在泛型类型约束中真正表达“仅允许string为有效值的值类型”的约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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