欢迎来到传世资源网!
加载中...
正在加载,请耐心等待...
本站为收藏、学习站,如有侵权,请联系管理员删除!

C# 泛型MakeGeneric方法应用实例

介绍 评论 失效链接反馈

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

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