定义以下泛型:
Internal sealed class DictionaryStringKey:Dictionary{}
哪个选项不会抛出异常()
Type t=typeof(Dictionary<,>); Object o=Activator.CreateInstance(t);
Type t=typeof(DictionaryStringKey<>); Object o=Activator.CreateInstance(t);
Type t=typeof(DictionaryStringKey<Guid>); Object o=Activator.CreateInstance(t);
internal sealed class DictionaryStringKey<TValue> : Dictionary<String, TValue> { } public static class Program { static void Main(string[] args) { Object o = null; //Dictionary<,>是一个开放类型,它有两个类型参数 Type t = typeof(Dictionary<,>); //尝试创建该类型的一个实例失败 o = CreateInstance(t); Console.WriteLine(); //DictionaryStringKey是一个开放类型,他有一个类型参数 t = typeof(DictionaryStringKey<>); //尝试创建该类型的一个实例失败 o = CreateInstance(t); Console.WriteLine(); //DictionaryStringKey<Guid>是一个封闭类型 t = typeof(DictionaryStringKey<Guid>); //尝试创建该类型的一个实例成功 o = CreateInstance(t); //证明它确实能够工作 Console.WriteLine(" 对象类型:"+o.GetType()); } private static Object CreateInstance(Type t) { Object o = null; try { o = Activator.CreateInstance(t); Console.WriteLine("已创建{0}的实例。",t.ToString()); } catch (ArgumentException e) { Console.WriteLine(e.Message); } return o; } }
// 异常 // Cannot create an instance of System.Collections.Generic.Dictionary`2[TKey,TValue] // because Type.ContainsGenericParameters is true. // Type t = typeof(Dictionary<,>); // Object o = Activator.CreateInstance(t); // 异常 // 错误原因同上 // Type t = typeof(DictionaryStringKey<>); // Object o = Activator.CreateInstance(t); Type t = typeof(DictionaryStringKey<Guid>); Object o = Activator.CreateInstance(t);