代码之家  ›  专栏  ›  技术社区  ›  rohancragg

将泛型字典作为参数传递给需要IDictionary的方法可以吗

  •  3
  • rohancragg  · 技术社区  · 16 年前

    AssemblyInstaller.Install需要System.Collections.IDictionary。

    例如

    using System.Collections.Generic;
    using System.Configuration.Install;
    using System.Reflection;
    using AssemblyWithInstaller;
    
    namespace InstallerDemo
    {
        class InstallerDemo
        {
            static void Main(string[] args)
            {
                var savedState = new Dictionary<object, object>();
                // i.e. as opposed to something that implements IDictionary:
                //var savedState = new System.Collections.Hashtable()
                var assembly = Assembly.GetAssembly(typeof (MyInstaller));
                var ai = new AssemblyInstaller(assembly, new[] {"/LogFile=install.log"});
                ai.Install(savedState);
                ai.Commit(savedState);
            }
        }
    }
    

    此外,编译器对此贴花没有问题:

    var savedState = new Dictionary<string, object>();
    

    但是,如果有人使用字符串以外的东西作为键,在运行时会发生什么不好的事情吗?


    使现代化

    var savedState=新字典<字符串,对象>();
    

    void IDictionary.Add(object key, object value)
    {
        Dictionary<TKey, TValue>.VerifyKey(key);
        Dictionary<TKey, TValue>.VerifyValueType(value);
        this.Add((TKey) key, (TValue) value);
    }
    

    …因此,在验证键时,如果键的类型与声明泛型字典的特定专门化时使用的类型不匹配(同样,对于值的类型),它将引发异常:

    private static void VerifyKey(object key)
    {
        if (key == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
        }
        if (!(key is TKey))
        {
            ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
        }
    }
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   Bobby    16 年前

    任何 字典传给了他。至少这是我的观点……如果我使用接口,我需要能够处理它的任何实现。

        2
  •  2
  •   Jon Skeet    16 年前

    这是因为 Dictionary<TKey, TValue> 工具 IDictionary IDictionary.Add(object, object) ArgumentException .

    请注意 IDictionary<TKey, TValue> 接口本身不扩展 词典 -只是 字典<TKey,TValue> 工具 词典 .