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/