Exemple #1
0
        public static void Main()
        {
            // DictionaryStringKey<Guid> e' um tipo fechado (closed type)
            // DictionaryStringKey<Guid> deriva do tipo fechado Dictionary<String, Guid>
            DictionaryStringKey <Guid> d = new DictionaryStringKey <Guid>();
            object o     = null;
            Type   type1 = typeof(Dictionary <,>);

            o = CreateInstance(type1); // Erro, pois Dictionary<,> e' um tipo aberto, nao e' possivel criar instancias
            Console.WriteLine();

            Type type2 = typeof(DictionaryStringKey <>);

            o = CreateInstance(type2); // Erro, pois DictionaryStringKey<> e' um tipo aberto, nao e' possivel criar instancias
            Console.WriteLine();

            Type type3 = typeof(DictionaryStringKey <Guid>); // Closed type

            o = CreateInstance(type3);                       // OK
            Console.WriteLine("o.GetType() = {0}", o.GetType());
            Console.WriteLine();

            // Nota:
            // Nao existe relacao de heranca entre um closed type e o seu opened type.
            //
            Console.WriteLine("type2.IsAssignableFrom(type3) ? {0}", type2.IsAssignableFrom(type3)); // false
            // Os tipos base de um tipo fechado sao os mesmos do tipo aberto substituindo os parametros de
            // tipo pelos argumentos usados.
            Console.WriteLine("typeof(Dictionary<String, Guid>).IsAssignableFrom(type3) ? {0}",
                              typeof(Dictionary <String, Guid>).IsAssignableFrom(type3)); // true
        }
Exemple #2
0
        public static void TestRun()
        {
            object o = null;
            // Dictionary<,>是一个开放类型,它有2个类型参数
            Type t1 = typeof(Dictionary <,>);

            // 创建开放类型的实例(创建失败,出现异常)
            o = CreateInstance(t1);
            Console.WriteLine();

            // DictionaryStringKey<>也是一个开放类型,但它有1个类型参数
            Type t2 = typeof(DictionaryStringKey <>);

            // 创建该类型的实例(同样会失败,出现异常)
            o = CreateInstance(t2);
            Console.WriteLine();

            // DictionaryStringKey<int>是一个封闭类型
            Type t3 = typeof(DictionaryStringKey <int>);

            // 创建封闭类型的一个实例(成功)
            o = CreateInstance(t3);
            Console.WriteLine($"对象类型={o.GetType()}");
            //测试泛型类
            DictionaryStringKey <int> dic = new DictionaryStringKey <int>("werwer");

            dic.Add("a", 111);
            dic.Add("b", 222);

            Type t4 = typeof(TestClass1);

            // 创建抽象类的实例(创建失败,出现异常)
            o = CreateInstance(t4);

            Console.ReadKey();
        }