【发布时间】:2009-10-29 09:22:50
【问题描述】:
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);
}
}
}
此外,编译器对此 decalation 没有任何问题:
var savedState = new Dictionary<string, object>();
但是如果有人使用字符串以外的东西作为键,在运行时会发生什么不好的事情吗?
更新 [救援反射器]
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));
}
}
【问题讨论】:
标签: c# generics collections