c# - 将通用字典作为参数传递给需要 IDictionary 的方法是否可以

标签 c# generics collections

AssemblyInstaller.Install 需要一个 System.Collections.IDictionary。

我对使用 Hashtable 等非通用集合“过敏”是否正确,还是我应该克服自己?!

例如

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

此外,编译器对这个 decalration 没有问题:

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

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


更新 [Reflector to rescue]

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

确认 Jon 所说的,Dictionary 实现 IDictionary 如下:

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

最佳答案

由于安装程序正在接受一个 IDictionary 对象,它应该能够处理传递给他的任何 字典。至少这是我的观点……如果我采用接口(interface),我需要能够处理它的任何实现。

此外,我建议您尝试一下。

关于c# - 将通用字典作为参数传递给需要 IDictionary 的方法是否可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1642497/

相关文章:

java - 将静态字段作为通用类型传递

java - 如何使用 selenium webdriver 将 HashSet 和 LinkedHashSet 与 List<WebElement> 结合使用

java - 存储键、值对并通过索引或键名访问其对象的最佳 Java 集合

java - 泛型映射 : read and write

ios - 如何在运行时通过 Selector 在 Swift 中调用泛型函数?

c# - 如何将 Entity Framework 设置为使用可选外键级联删除?

Serialport 写入单字节后的 c# 事件处理程序

C# - 需要由一个且只有一个逗号分隔的字符格式的字符串

C# 通用接口(interface)转换问题

c# - DefaultIfEmpty 不起作用