【问题标题】:How to make dictionary extension-methods?如何制作字典扩展方法?
【发布时间】:2012-06-02 15:01:06
【问题描述】:

我正在尝试编写一个独立于键/值数据类型工作的Dictionary 扩展。我尝试使用 object 数据类型传递它,假设它适用于任何类型。

我的代码:

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

【问题讨论】:

    标签: c# dictionary extension-methods


    【解决方案1】:

    您只需将方法设为通用:

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

    请注意,它仅在 key 类型中是通用的,因为值将 具有string(或可能为 objectstring 实现的接口,我猜)假设你要向它添加一个字符串值。

    不幸的是,您无法在泛型类型约束中真正表达“仅允许 string 为有效值的值类型”的约束。

    【讨论】:

    • 感谢您的回答。 :) 我已更改代码,但更改为Dictionary&lt;WaringType, string&gt;(); 类型的变量,其中WaringTypeenum,我收到错误:'System.Collections.Generic.Dictionary&lt;myclass.WaringType,string&gt;' does not contain a definition for 'AddFormat' and no extension method 'AddFormat' accepting a first argument of type 'System.Collections.Generic.Dictionary&lt;myclass.WaringType,string&gt;' could be found (are you missing a using directive or an assembly reference?)
    • 当我调用该方法时:ErrMessages.AddFormat(WaringType.FatalError, "{0} foo {1} baa etc", a.Name, a.Value);
    • 确保有一个using 语句,如果您在不同的命名空间中工作,则可以使具有扩展方法的类可见。尝试将您的扩展方法显式调用为 DictionaryExtensionsClass.AddFormat(theDictionary, key, format, ...); 以检查可见性。
    • @Wormbo:谢谢。当我在 autcompletaion 上看到 DictionaryExtensionsClass 时,我看到了方法名称和我的错字。我在重写代码时建议由 Jon Skeet 我在 FormattAdd() 方法名称上添加了一个 t。很抱歉给您带来不便。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2017-04-17
    • 2010-11-14
    • 2020-08-09
    相关资源
    最近更新 更多