找传奇、传世资源到传世资源站!

C# 泛型MakeGeneric方法应用实例

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

from clipboard
using System;using System.Reflection;using System.Collections.Generic;using MakeGenericTypeTest;using MakeGenericTypeTest.InterFace;public class Test{ public static void Main() { Type[] tys = Activator.CreateInstance(typeof(SayHello), "big big word").GetType().GetInterface(typeof(ISay<>).Name).GetGenericArguments(); Type ty = typeof(BigWord<>).MakeGenericType(tys); BigWord<ISayHello> obj = (BigWord<ISayHello>)Activator.CreateInstance(ty); Console.WriteLine(obj.SayHello()); Console.WriteLine("\r\n--- Create a constructed type from the generic Dictionary type."); // Create a type object representing the generic Dictionary // type, by omitting the type arguments (but keeping the // comma that separates them, so the compiler can infer the // number of type parameters). Type generic = typeof(Dictionary<,>); DisplayTypeInfo(generic); // Create an array of types to substitute for the type // parameters of Dictionary. The key is of type string, and // the type to be contained in the Dictionary is Test. Type[] typeArgs = { typeof(string), typeof(Test) }; // Create a Type object representing the constructed generic // type. Type constructed = generic.MakeGenericType(typeArgs); DisplayTypeInfo(constructed); // Compare the type objects obtained above to type objects // obtained using typeof() and GetGenericTypeDefinition(). Console.WriteLine("\r\n--- Compare types obtained by different methods:"); Type t = typeof(Dictionary<String, Test>); Console.WriteLine("\tAre the constructed types equal? {0}", t == constructed); Console.WriteLine("\tAre the generic types equal? {0}", t.GetGenericTypeDefinition() == generic); Console.ReadLine(); } private static void DisplayTypeInfo(Type t) { Console.WriteLine("\r\n{0}", t); Console.WriteLine("\tIs this a generic type definition? {0}", t.IsGenericTypeDefinition); Console.WriteLine("\tIs it a generic type? {0}", t.IsGenericType); Type[] typeArguments = t.GetGenericArguments(); Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length); foreach (Type tParam in typeArguments) { Console.WriteLine("\t\t{0}", tParam); } }}/* This example produces the following output:--- Create a constructed type from the generic Dictionary type.System.Collections.Generic.Dictionary`2[TKey,TValue] Is this a generic type definition? True Is it a generic type? True List type arguments (2): TKey TValueSystem.Collections.Generic.Dictionary`2[System.String, Test] Is this a generic type definition? False Is it a generic type? True List type arguments (2): System.String Test--- Compare types obtained by different methods: Are the constructed types equal? True Are the generic types equal? True */

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复