自助建站网站建设每天三分钟新闻天下事

张小明 2025/12/31 7:39:38
自助建站网站建设,每天三分钟新闻天下事,个人旅游网站模版,怎么做一个企业的网站反射#xff08;Reflection#xff09;是 C# 的 “元编程” 能力#xff0c;允许程序在运行时获取类型信息、调用方法、创建实例#xff1b;泛型#xff08;Generic#xff09;则是 “类型参数化”#xff0c;实现类型安全的代码复用。两者结合可突破静态泛型的限制Reflection是 C# 的 “元编程” 能力允许程序在运行时获取类型信息、调用方法、创建实例泛型Generic则是 “类型参数化”实现类型安全的代码复用。两者结合可突破静态泛型的限制实现动态绑定泛型参数、调用泛型方法、操作泛型成员是框架开发如 DI 容器、ORM、序列化的核心技术。本文将从 “基础概念→核心 API→分场景超详细案例→底层原理→避坑指南” 全维度讲解所有案例均为可直接运行的控制台程序每一行代码都附带注释和原理说明。一、核心概念前置在开始案例前先明确反射操作泛型的核心术语避免概念混淆术语定义示例泛型定义未绑定类型未指定具体泛型参数的泛型类型 / 方法仅表示 “模板”无法直接实例化 / 调用typeof(GenericClass)、MethodInfo泛型方法定义已绑定类型 / 方法绑定了具体泛型参数的泛型类型 / 方法可实例化 / 调用typeof(GenericClassint)、绑定了string的泛型方法泛型参数Type Argument绑定到泛型定义的具体类型如 int、stringMakeGenericType(typeof(int))中的 int泛型形参Type Parameter泛型定义中的占位符如T、Uclass GenericClassT中的 T二、核心 API 全解析反射操作泛型的 “工具箱”以下是反射操作泛型的核心 API按 “类型操作→方法操作→成员操作” 分类每个 API 附带用途和使用场景2.1 泛型类型操作 APIAPI用途Type.IsGenericType判断类型是否是已绑定的泛型类型如GenericClassint返回 trueType.IsGenericTypeDefinition判断类型是否是泛型定义如GenericClass返回 trueType.GetGenericTypeDefinition()从已绑定类型获取泛型定义如GenericClassint→GenericClassType.MakeGenericType(params Type[])绑定泛型参数从泛型定义生成已绑定类型核心 APIType.GetGenericArguments()获取泛型参数数组已绑定类型返回具体类型泛型定义返回形参2.2 泛型方法操作 APIAPI用途MethodInfo.IsGenericMethod判断方法是否是泛型方法已绑定 / 未绑定均返回 trueMethodInfo.IsGenericMethodDefinition判断方法是否是泛型方法定义未绑定参数MethodInfo.MakeGenericMethod(params Type[])绑定泛型参数从泛型方法定义生成已绑定方法核心 APIMethodInfo.GetGenericArguments()获取方法的泛型参数数组2.3 实例 / 成员操作 APIAPI用途Activator.CreateInstance(Type, params object[])创建泛型类型实例支持无参 / 带参构造MethodInfo.Invoke(object, object[])调用泛型方法实例方法传实例静态方法传 nullPropertyInfo.GetValue(object)/SetValue(object)读写泛型类型的属性三、控制台案例分 8 个核心场景所有案例基于同一控制台项目先定义测试用的泛型类型类、接口、方法再分场景演示反射操作。3.0 准备测试用泛型类型基础依赖先定义一套覆盖 “泛型类、泛型接口、泛型方法实例 / 静态 / 重载、泛型属性 / 字段” 的测试类型后续所有反射操作均基于此using System; using System.Collections.Generic; using System.Reflection; namespace ReflectionGenericUltraDetail { #region 测试用泛型类型定义核心依赖 /// summary /// 泛型测试类包含泛型字段、属性、构造函数、实例泛型方法、静态泛型方法、重载泛型方法 /// /summary /// typeparam nameT主泛型参数/typeparam public class GenericTestClassT { // 泛型字段 public T GenericField; // 泛型属性 public T GenericProperty { get; set; } // 非泛型属性对比 public int NonGenericProperty { get; set; } 0; #region 构造函数无参/单参/多参 /// summary /// 无参构造函数 /// /summary public GenericTestClass() { Console.WriteLine($【构造函数】GenericTestClass{typeof(T).Name} 无参构造执行); } /// summary /// 单参构造函数泛型参数类型 /// /summary /// param nameinitValue泛型类型的初始值/param public GenericTestClass(T initValue) { GenericField initValue; GenericProperty initValue; Console.WriteLine($【构造函数】GenericTestClass{typeof(T).Name} 单参构造执行初始值{initValue}); } /// summary /// 多参构造函数泛型非泛型参数 /// /summary /// param nameinitValue泛型初始值/param /// param namenonGenericValue非泛型int值/param public GenericTestClass(T initValue, int nonGenericValue) { GenericField initValue; GenericProperty initValue; NonGenericProperty nonGenericValue; Console.WriteLine($【构造函数】GenericTestClass{typeof(T).Name} 多参构造执行泛型值{initValue}非泛型值{nonGenericValue}); } #endregion #region 实例方法泛型/非泛型/重载 /// summary /// 非泛型实例方法 /// /summary public void NonGenericInstanceMethod() { Console.WriteLine($【实例方法】非泛型方法执行泛型类型{typeof(T).Name}GenericProperty值{GenericProperty}); } /// summary /// 泛型实例方法单泛型参数 /// /summary /// typeparam nameU方法级泛型参数/typeparam /// param nameinput1类泛型参数T类型/param /// param nameinput2方法泛型参数U类型/param public void GenericInstanceMethodU(T input1, U input2) { Console.WriteLine($【实例方法】泛型方法{typeof(U).Name}执行输入1{typeof(T).Name}{input1}输入2{typeof(U).Name}{input2}); } /// summary /// 泛型实例方法重载版 /// /summary /// typeparam nameU方法级泛型参数/typeparam /// typeparam nameV第二个方法级泛型参数/typeparam /// param nameinput1T类型/param /// param nameinput2U类型/param /// param nameinput3V类型/param public void GenericInstanceMethodU, V(T input1, U input2, V input3) { Console.WriteLine($【实例方法】泛型方法{typeof(U).Name},{typeof(V).Name}重载版执行输入1{input1}输入2{input2}输入3{input3}); } #endregion #region 静态方法泛型/非泛型 /// summary /// 非泛型静态方法 /// /summary /// param namemessage字符串参数/param public static void NonGenericStaticMethod(string message) { Console.WriteLine($【静态方法】非泛型静态方法执行消息{message}); } /// summary /// 泛型静态方法 /// /summary /// typeparam nameW静态方法泛型参数/typeparam /// param namevalueW类型参数/param public static void GenericStaticMethodW(W value) { Console.WriteLine($【静态方法】泛型静态方法{typeof(W).Name}执行值{value}); } #endregion } /// summary /// 泛型接口测试泛型接口反射 /// /summary /// typeparam nameT接口泛型参数/typeparam public interface IGenericTestInterfaceT { T GetData(); void SetData(T data); void GenericInterfaceMethodU(T input, U output); } /// summary /// 泛型接口实现类 /// /summary /// typeparam nameT实现类泛型参数/typeparam public class GenericInterfaceImplementT : IGenericTestInterfaceT { private T _data; public T GetData() { Console.WriteLine($【接口实现】GetData()执行返回值{_data}); return _data; } public void SetData(T data) { _data data; Console.WriteLine($【接口实现】SetData()执行设置值{data}); } public void GenericInterfaceMethodU(T input, U output) { Console.WriteLine($【接口实现】泛型接口方法{typeof(U).Name}执行输入{input}输出{output}); } } #endregion class Program { static void Main(string[] args) { Console.WriteLine( 场景1泛型类型的反射基础操作 ); Scene1_GenericTypeBasicOperations(); Console.WriteLine(\n 场景2动态创建泛型类实例全构造函数 ); Scene2_CreateGenericInstance(); Console.WriteLine(\n 场景3动态调用泛型实例方法含重载 ); Scene3_CallGenericInstanceMethod(); Console.WriteLine(\n 场景4动态调用泛型静态方法 ); Scene4_CallGenericStaticMethod(); Console.WriteLine(\n 场景5反射操作泛型字段/属性 ); Scene5_ReflectGenericFieldProperty(); Console.WriteLine(\n 场景6泛型接口的反射操作 ); Scene6_ReflectGenericInterface(); Console.WriteLine(\n 场景7嵌套泛型的反射处理 ); Scene7_HandleNestedGeneric(); Console.WriteLine(\n 场景8泛型方法重载的精准获取 ); Scene8_GetOverloadGenericMethod(); Console.ReadKey(); }3.1 场景 1泛型类型的反射基础操作目标掌握 “泛型定义” 与 “已绑定类型” 的区分、核心属性判断、泛型参数获取。/// summary /// 场景1泛型类型的反射基础操作泛型定义/已绑定类型区分、参数获取 /// /summary static void Scene1_GenericTypeBasicOperations() { // 1. 获取泛型定义未绑定类型typeof(类名)注意内无参数 Type genericDefinition typeof(GenericTestClass); Console.WriteLine($1. 泛型定义类型名{genericDefinition.FullName}); Console.WriteLine($ - 是否是泛型定义{genericDefinition.IsGenericTypeDefinition}); Console.WriteLine($ - 是否是泛型类型{genericDefinition.IsGenericType}); // 泛型定义也是泛型类型 Console.WriteLine($ - 泛型形参数量{genericDefinition.GetGenericArguments().Length}); // 1个形参T Console.WriteLine($ - 泛型形参名称{genericDefinition.GetGenericArguments()[0].Name}); // T // 2. 绑定泛型参数生成已绑定类型核心MakeGenericType Type boundType_Int genericDefinition.MakeGenericType(typeof(int)); Console.WriteLine($\n2. 绑定int后的已绑定类型名{boundType_Int.FullName}); Console.WriteLine($ - 是否是泛型定义{boundType_Int.IsGenericTypeDefinition}); // false已绑定 Console.WriteLine($ - 是否是泛型类型{boundType_Int.IsGenericType}); // true Console.WriteLine($ - 泛型实参类型{boundType_Int.GetGenericArguments()[0].Name}); // Int32具体类型 // 3. 从已绑定类型反推泛型定义GetGenericTypeDefinition Type derivedDefinition boundType_Int.GetGenericTypeDefinition(); Console.WriteLine($\n3. 从已绑定类型反推的泛型定义{derivedDefinition.FullName}); Console.WriteLine($ - 与原泛型定义是否相同{derivedDefinition genericDefinition}); // true // 4. 非泛型类型的对比验证属性 Type nonGenericType typeof(string); Console.WriteLine($\n4. 非泛型类型string); Console.WriteLine($ - 是否是泛型类型{nonGenericType.IsGenericType}); // false Console.WriteLine($ - 是否是泛型定义{nonGenericType.IsGenericTypeDefinition}); // false }运行结果1. 泛型定义类型名ReflectionGenericUltraDetail.GenericTestClass1 - 是否是泛型定义True - 是否是泛型类型True - 泛型形参数量1 - 泛型形参名称T 2. 绑定int后的已绑定类型名ReflectionGenericUltraDetail.GenericTestClass1[[System.Int32, System.Private.CoreLib, Version7.0.0.0, Cultureneutral, PublicKeyToken7cec85d7bea7798e]] - 是否是泛型定义False - 是否是泛型类型True - 泛型实参类型Int32 3. 从已绑定类型反推的泛型定义ReflectionGenericUltraDetail.GenericTestClass1 - 与原泛型定义是否相同True 4. 非泛型类型string - 是否是泛型类型False - 是否是泛型定义False核心说明泛型定义是 “模板”无法直接实例化Activator.CreateInstance(typeof(GenericTestClass))会报错必须通过MakeGenericType绑定具体类型生成 “已绑定类型” 后才能实例化 / 调用方法GetGenericTypeDefinition()是 “反向操作”可从已绑定类型还原泛型定义用于缓存泛型模板。3.2 场景 2动态创建泛型类实例全构造函数目标掌握无参、单参、多参构造函数的泛型实例创建解决 “构造函数参数匹配” 问题。/// summary /// 场景2动态创建泛型类实例无参/单参/多参构造函数 /// /summary static void Scene2_CreateGenericInstance() { // 步骤1获取泛型定义并绑定int类型已绑定类型 Type genericDefinition typeof(GenericTestClass); Type boundType_Int genericDefinition.MakeGenericType(typeof(int)); // 子场景1无参构造创建实例 Console.WriteLine(【子场景1】无参构造创建实例); object instance_NoParam Activator.CreateInstance(boundType_Int); Console.WriteLine($ - 实例类型{instance_NoParam.GetType().FullName}); Console.WriteLine($ - 转换为强类型{instance_NoParam is GenericTestClassint}); // true // 子场景2单参构造创建实例参数为泛型类型 Console.WriteLine(\n【子场景2】单参构造创建实例int类型参数99); object instance_SingleParam Activator.CreateInstance(boundType_Int, 99); // 第二个参数是构造函数参数数组 // 验证获取GenericProperty属性值后续场景会详解属性反射此处先强转 GenericTestClassint strongType_SingleParam instance_SingleParam as GenericTestClassint; Console.WriteLine($ - 实例的GenericProperty值{strongType_SingleParam.GenericProperty}); // 99 // 子场景3多参构造创建实例泛型参数非泛型参数 Console.WriteLine(\n【子场景3】多参构造创建实例int88非泛型int1000); object instance_MultiParam Activator.CreateInstance(boundType_Int, 88, 1000); GenericTestClassint strongType_MultiParam instance_MultiParam as GenericTestClassint; Console.WriteLine($ - GenericProperty值{strongType_MultiParam.GenericProperty}); // 88 Console.WriteLine($ - NonGenericProperty值{strongType_MultiParam.NonGenericProperty}); // 1000 // 扩展绑定string类型创建单参实例 Console.WriteLine(\n【扩展】绑定string类型单参构造参数\Hello Reflection\); Type boundType_String genericDefinition.MakeGenericType(typeof(string)); object instance_String Activator.CreateInstance(boundType_String, Hello Reflection); GenericTestClassstring strongType_String instance_String as GenericTestClassstring; Console.WriteLine($ - String类型实例的GenericProperty{strongType_String.GenericProperty}); // 异常场景演示构造函数参数类型不匹配 try { Console.WriteLine(\n【异常演示】构造函数参数类型不匹配int类型实例传string参数); Activator.CreateInstance(boundType_Int, 错误的字符串参数); } catch (TargetInvocationException ex) { Console.WriteLine($ - 异常信息{ex.InnerException.Message}); // 无法将string转换为int } }运行结果【子场景1】无参构造创建实例 【构造函数】GenericTestClassInt32 无参构造执行 - 实例类型ReflectionGenericUltraDetail.GenericTestClass1[[System.Int32, System.Private.CoreLib, Version7.0.0.0, Cultureneutral, PublicKeyToken7cec85d7bea7798e]] - 转换为强类型True 【子场景2】单参构造创建实例int类型参数99 【构造函数】GenericTestClassInt32 单参构造执行初始值99 - 实例的GenericProperty值99 【子场景3】多参构造创建实例int88非泛型int1000 【构造函数】GenericTestClassInt32 多参构造执行泛型值88非泛型值1000 - GenericProperty值88 - NonGenericProperty值1000 【扩展】绑定string类型单参构造参数Hello Reflection 【构造函数】GenericTestClassString 单参构造执行初始值Hello Reflection - String类型实例的GenericPropertyHello Reflection 【异常演示】构造函数参数类型不匹配int类型实例传string参数 - 异常信息Object of type System.String cannot be converted to type System.Int32.核心说明Activator.CreateInstance(Type, params object[])是创建实例的核心方法第二个参数是构造函数的参数数组构造函数参数类型必须与已绑定类型的泛型参数匹配否则会抛出TargetInvocationException内层是类型转换异常强转as GenericTestClassint是反射后使用实例的常用方式前提是知道泛型参数类型。3.3 场景 3动态调用泛型实例方法含重载目标掌握 “泛型方法定义” 的获取、方法级泛型参数的绑定、实例方法的调用。/// summary /// 场景3动态调用泛型实例方法含方法级泛型参数绑定 /// /summary static void Scene3_CallGenericInstanceMethod() { // 步骤1创建泛型类实例绑定int类型单参构造100 Type boundType_Int typeof(GenericTestClassint); object instance Activator.CreateInstance(boundType_Int, 100); // 子场景1调用非泛型实例方法基础 Console.WriteLine(【子场景1】调用非泛型实例方法); MethodInfo nonGenericMethod boundType_Int.GetMethod(NonGenericInstanceMethod); nonGenericMethod.Invoke(instance, null); // 第二个参数方法参数数组无参则传null // 子场景2调用泛型实例方法单泛型参数U Console.WriteLine(\n【子场景2】调用泛型实例方法GenericInstanceMethodU绑定U为string); // 步骤1获取泛型方法定义未绑定方法 MethodInfo genericMethodDef boundType_Int.GetMethod(GenericInstanceMethod); Console.WriteLine($ - 方法是否是泛型定义{genericMethodDef.IsGenericMethodDefinition}); // true Console.WriteLine($ - 方法泛型形参数量{genericMethodDef.GetGenericArguments().Length}); // 1U // 步骤2绑定方法级泛型参数U→string MethodInfo boundMethod genericMethodDef.MakeGenericMethod(typeof(string)); Console.WriteLine($ - 绑定后的方法名{boundMethod.Name}); // 步骤3调用方法参数数组input1100Tintinput2测试字符串Ustring boundMethod.Invoke(instance, new object[] { 100, 测试字符串 }); // 子场景3调用重载的泛型实例方法UV两个泛型参数 Console.WriteLine(\n【子场景3】调用重载泛型实例方法GenericInstanceMethodU,VUdoubleVDateTime); // 注意GetMethod默认获取第一个匹配名称的方法重载需指定参数类型场景8详解 MethodInfo genericMethodDef_Overload boundType_Int.GetMethod( GenericInstanceMethod, new Type[] { typeof(int), typeof(object), typeof(object) } // 参数类型Tint, Uobject, Vobject临时占位 ); // 绑定方法泛型参数UdoubleVDateTime MethodInfo boundMethod_Overload genericMethodDef_Overload.MakeGenericMethod(typeof(double), typeof(DateTime)); // 调用方法input1200intinput23.14doubleinput3当前时间DateTime boundMethod_Overload.Invoke(instance, new object[] { 200, 3.14, DateTime.Now }); }运行结果【构造函数】GenericTestClassInt32 单参构造执行初始值100 【子场景1】调用非泛型实例方法 【实例方法】非泛型方法执行泛型类型Int32GenericProperty值100 【子场景2】调用泛型实例方法GenericInstanceMethodU绑定U为string - 方法是否是泛型定义True - 方法泛型形参数量1 - 绑定后的方法名GenericInstanceMethod 【实例方法】泛型方法String执行输入1Int32100输入2String测试字符串 【子场景3】调用重载泛型实例方法GenericInstanceMethodU,VUdoubleVDateTime 【实例方法】泛型方法Double,DateTime重载版执行输入1200输入23.14输入32025/12/16 15:30:00核心说明泛型方法的操作分三步获取方法定义→绑定方法级泛型参数→调用InvokeMethodInfo.Invoke(object instance, object[] parameters)第一个参数实例方法传实例静态方法传null第二个参数方法参数数组顺序必须与方法定义一致重载方法的精准获取需指定参数类型场景 8 详解。3.4 场景 4动态调用泛型静态方法目标掌握静态泛型方法的获取、绑定、调用无需实例。/// summary /// 场景4动态调用泛型静态方法无需创建实例 /// /summary static void Scene4_CallGenericStaticMethod() { // 步骤1获取已绑定类型int Type boundType_Int typeof(GenericTestClassint); // 子场景1调用非泛型静态方法 Console.WriteLine(【子场景1】调用非泛型静态方法); MethodInfo nonGenericStaticMethod boundType_Int.GetMethod(NonGenericStaticMethod); nonGenericStaticMethod.Invoke(null, new object[] { 静态方法测试消息 }); // 实例参数传null // 子场景2调用泛型静态方法 Console.WriteLine(\n【子场景2】调用泛型静态方法GenericStaticMethodW绑定W为bool); // 步骤1获取泛型静态方法定义 MethodInfo genericStaticMethodDef boundType_Int.GetMethod(GenericStaticMethod); Console.WriteLine($ - 是否是泛型方法定义{genericStaticMethodDef.IsGenericMethodDefinition}); // true // 步骤2绑定方法泛型参数W→bool MethodInfo boundStaticMethod genericStaticMethodDef.MakeGenericMethod(typeof(bool)); // 步骤3调用静态方法实例参数null方法参数true boundStaticMethod.Invoke(null, new object[] { true }); // 扩展绑定不同泛型参数WDateTime Console.WriteLine(\n【扩展】绑定WDateTime调用泛型静态方法); MethodInfo boundStaticMethod_DateTime genericStaticMethodDef.MakeGenericMethod(typeof(DateTime)); boundStaticMethod_DateTime.Invoke(null, new object[] { DateTime.Now }); }运行结果【子场景1】调用非泛型静态方法 【静态方法】非泛型静态方法执行消息静态方法测试消息 【子场景2】调用泛型静态方法GenericStaticMethodW绑定W为bool - 是否是泛型方法定义True 【静态方法】泛型静态方法Boolean执行值True 【扩展】绑定WDateTime调用泛型静态方法 【静态方法】泛型静态方法DateTime执行值2025/12/16 15:30:00核心说明静态方法调用时Invoke的第一个参数必须传null泛型静态方法的绑定逻辑与实例泛型方法一致区别仅在于 “无需实例”静态方法属于类型本身与实例无关因此无需创建泛型类实例。3.5 场景 5反射操作泛型字段 / 属性目标掌握泛型类型的字段、属性的读取和修改解决 “动态访问泛型成员” 问题。/// summary /// 场景5反射操作泛型字段/属性读取/修改 /// /summary static void Scene5_ReflectGenericFieldProperty() { // 步骤1创建泛型实例绑定string类型单参构造初始值 Type boundType_String typeof(GenericTestClassstring); object instance Activator.CreateInstance(boundType_String, 初始值); // 子场景1操作泛型字段GenericField Console.WriteLine(【子场景1】操作泛型字段GenericField); FieldInfo genericField boundType_String.GetField(GenericField); // 读取字段值 object fieldValue genericField.GetValue(instance); Console.WriteLine($ - 原始字段值{fieldValue}); // 修改字段值 genericField.SetValue(instance, 修改后的字段值); Console.WriteLine($ - 修改后的字段值{genericField.GetValue(instance)}); // 子场景2操作泛型属性GenericProperty Console.WriteLine(\n【子场景2】操作泛型属性GenericProperty); PropertyInfo genericProperty boundType_String.GetProperty(GenericProperty); // 读取属性值 object propValue genericProperty.GetValue(instance); Console.WriteLine($ - 原始属性值{propValue}); // 修改属性值 genericProperty.SetValue(instance, 修改后的属性值); Console.WriteLine($ - 修改后的属性值{genericProperty.GetValue(instance)}); // 子场景3操作非泛型属性NonGenericProperty Console.WriteLine(\n【子场景3】操作非泛型属性NonGenericProperty); PropertyInfo nonGenericProp boundType_String.GetProperty(NonGenericProperty); Console.WriteLine($ - 原始值{nonGenericProp.GetValue(instance)}); // 默认0 nonGenericProp.SetValue(instance, 999); Console.WriteLine($ - 修改后值{nonGenericProp.GetValue(instance)}); // 999 // 异常场景字段/属性不存在 try { Console.WriteLine(\n【异常演示】获取不存在的字段); boundType_String.GetField(不存在的字段); } catch (NullReferenceException ex) { Console.WriteLine($ - 异常{ex.Message}); } }运行结果【构造函数】GenericTestClassString 单参构造执行初始值初始值 【子场景1】操作泛型字段GenericField - 原始字段值初始值 - 修改后的字段值修改后的字段值 【子场景2】操作泛型属性GenericProperty - 原始属性值初始值 - 修改后的属性值修改后的属性值 【子场景3】操作非泛型属性NonGenericProperty - 原始值0 - 修改后值999 【异常演示】获取不存在的字段 - 异常Object reference not set to an instance of an object.核心说明FieldInfo.GetValue(object)/SetValue(object, object)读取 / 修改字段值参数为实例和新值PropertyInfo.GetValue(object)/SetValue(object, object)读取 / 修改属性值逻辑与字段一致泛型字段 / 属性的类型由已绑定类型的泛型参数决定如绑定 string 则字段类型为 string获取成员时名称必须完全匹配区分大小写否则返回null调用GetValue会抛空引用异常。3.6 场景 6泛型接口的反射操作目标掌握泛型接口的获取、接口方法的调用、实现类的反射。/// summary /// 场景6泛型接口的反射操作获取接口、调用接口方法 /// /summary static void Scene6_ReflectGenericInterface() { // 步骤1获取泛型接口实现类的已绑定类型绑定double Type implementType_Double typeof(GenericInterfaceImplementdouble); // 子场景1检查实现类是否实现泛型接口 Console.WriteLine(【子场景1】检查实现类是否实现泛型接口); // 获取接口类型GetInterface(接口名泛型参数个数)1表示1个泛型参数 Type genericInterfaceType implementType_Double.GetInterface(IGenericTestInterface1); Console.WriteLine($ - 是否实现IGenericTestInterfaceT{genericInterfaceType ! null}); // true Console.WriteLine($ - 接口泛型实参{genericInterfaceType.GetGenericArguments()[0].Name}); // Double // 子场景2创建实现类实例并调用接口方法 Console.WriteLine(\n【子场景2】调用泛型接口方法); object instance Activator.CreateInstance(implementType_Double); // 调用SetData方法 MethodInfo setDataMethod genericInterfaceType.GetMethod(SetData); setDataMethod.Invoke(instance, new object[] { 3.1415926 }); // 参数double类型的π // 调用GetData方法 MethodInfo getDataMethod genericInterfaceType.GetMethod(GetData); object data getDataMethod.Invoke(instance, null); Console.WriteLine($ - GetData返回值{data}); // 调用接口的泛型方法GenericInterfaceMethodU Console.WriteLine(\n【子场景3】调用接口的泛型方法); MethodInfo interfaceGenericMethodDef genericInterfaceType.GetMethod(GenericInterfaceMethod); // 绑定方法泛型参数U为string MethodInfo boundInterfaceMethod interfaceGenericMethodDef.MakeGenericMethod(typeof(string)); // 调用方法input2.718doubleoutput自然常数estring boundInterfaceMethod.Invoke(instance, new object[] { 2.718, 自然常数e }); }运行结果【子场景1】检查实现类是否实现泛型接口 - 是否实现IGenericTestInterfaceTTrue - 接口泛型实参Double 【子场景2】调用泛型接口方法 【接口实现】SetData()执行设置值3.1415926 【接口实现】GetData()执行返回值3.1415926 - GetData返回值3.1415926 【子场景3】调用接口的泛型方法 【接口实现】泛型接口方法String执行输入2.718输出自然常数e核心说明获取泛型接口需使用GetInterface(接口名泛型参数个数 )如IGenericTestInterface11表示接口有 1 个泛型参数泛型接口的方法调用逻辑与泛型类方法一致区别在于 “方法定义来自接口类型”实现类的泛型参数会自动传递给接口的泛型参数如GenericInterfaceImplementdouble→IGenericTestInterfacedouble。3.7 场景 7嵌套泛型的反射处理目标掌握嵌套泛型如ListDictionaryint, string的反射解决复杂泛型类型的操作问题。/// summary /// 场景7处理嵌套泛型如ListDictionaryint, string /// /summary static void Scene7_HandleNestedGeneric() { // 需求动态创建ListDictionaryint, string并添加元素 // 步骤1定义嵌套泛型的层级 // 内层Dictionaryint, string Type dictGenericDef typeof(Dictionary,); // 2个泛型参数 Type dictBoundType dictGenericDef.MakeGenericType(typeof(int), typeof(string)); // 外层ListDictionaryint, string Type listGenericDef typeof(List); // 1个泛型参数 Type listBoundType listGenericDef.MakeGenericType(dictBoundType); Console.WriteLine($嵌套泛型类型名{listBoundType.FullName}); // 步骤2创建List实例 object listInstance Activator.CreateInstance(listBoundType); Console.WriteLine($List实例类型{listInstance.GetType().Name}); // 步骤3创建Dictionary实例并添加元素 object dictInstance Activator.CreateInstance(dictBoundType); // 调用Dictionary的Add方法key1valueApple MethodInfo dictAddMethod dictBoundType.GetMethod(Add); dictAddMethod.Invoke(dictInstance, new object[] { 1, Apple }); dictAddMethod.Invoke(dictInstance, new object[] { 2, Banana }); // 步骤4将Dictionary添加到List中 MethodInfo listAddMethod listBoundType.GetMethod(Add); listAddMethod.Invoke(listInstance, new object[] { dictInstance }); // 步骤5验证List的Count属性 PropertyInfo listCountProp listBoundType.GetProperty(Count); int count (int)listCountProp.GetValue(listInstance); Console.WriteLine($ListDictionaryint,string的元素个数{count}); // 步骤6读取Dictionary的元素扩展 MethodInfo dictTryGetValueMethod dictBoundType.GetMethod(TryGetValue); object[] tryGetValueParams new object[] { 1, null }; // out参数初始为null bool success (bool)dictTryGetValueMethod.Invoke(dictInstance, tryGetValueParams); if (success) { Console.WriteLine($Dictionary中key1的值{tryGetValueParams[1]}); // out参数在索引1 } }运行结果嵌套泛型类型名System.Collections.Generic.List1[[System.Collections.Generic.Dictionary2[[System.Int32, System.Private.CoreLib, Version7.0.0.0, Cultureneutral, PublicKeyToken7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version7.0.0.0, Cultureneutral, PublicKeyToken7cec85d7bea7798e]], System.Private.CoreLib, Version7.0.0.0, Cultureneutral, PublicKeyToken7cec85d7bea7798e] List实例类型List1 ListDictionaryint,string的元素个数1 Dictionary中key1的值Apple核心说明嵌套泛型的处理需 “从内到外” 绑定泛型参数先绑定内层Dictionary再绑定外层Listout参数的处理调用方法时需传入长度匹配的数组out参数的值会填充到数组对应位置嵌套泛型是框架开发的高频场景如 ORM 的IQueryableDictionarystring, object。3.8 场景 8泛型方法重载的精准获取目标解决 “泛型方法重载时 GetMethod 获取错误方法” 的问题掌握 “参数类型匹配” 的精准获取方式。/// summary /// 场景8精准获取重载的泛型方法解决GetMethod默认获取第一个匹配方法的问题 /// /summary static void Scene8_GetOverloadGenericMethod() { // 步骤1获取已绑定类型int Type boundType_Int typeof(GenericTestClassint); // 问题GenericInstanceMethod有两个重载1个参数泛型/2个参数泛型默认GetMethod会获取第一个 // 解决通过参数类型数组精准匹配 Console.WriteLine(【子场景1】获取单参数泛型方法GenericInstanceMethodU(T, U)); // 参数类型数组TintUobject方法参数的类型U是泛型参数临时用object占位 Type[] singleParamMethodTypes new Type[] { typeof(int), typeof(object) }; MethodInfo singleParamGenericMethod boundType_Int.GetMethod( GenericInstanceMethod, singleParamMethodTypes ); Console.WriteLine($ - 方法是否是泛型定义{singleParamGenericMethod.IsGenericMethodDefinition}); Console.WriteLine($ - 方法参数个数{singleParamGenericMethod.GetParameters().Length}); // 2个参数T, U // 绑定U为DateTime并调用 MethodInfo boundSingleMethod singleParamGenericMethod.MakeGenericMethod(typeof(DateTime)); object instance Activator.CreateInstance(boundType_Int, 500); boundSingleMethod.Invoke(instance, new object[] { 500, DateTime.Now }); Console.WriteLine(\n【子场景2】获取双参数泛型方法GenericInstanceMethodU,V(T, U, V)); // 参数类型数组TintUobjectVobject Type[] doubleParamMethodTypes new Type[] { typeof(int), typeof(object), typeof(object) }; MethodInfo doubleParamGenericMethod boundType_Int.GetMethod( GenericInstanceMethod, doubleParamMethodTypes ); Console.WriteLine($ - 方法参数个数{doubleParamGenericMethod.GetParameters().Length}); // 3个参数T, U, V // 绑定UfloatVGuid并调用 MethodInfo boundDoubleMethod doubleParamGenericMethod.MakeGenericMethod(typeof(float), typeof(Guid)); boundDoubleMethod.Invoke(instance, new object[] { 600, 1.23f, Guid.NewGuid() }); } } }运行结果【子场景1】获取单参数泛型方法GenericInstanceMethodU(T, U) - 方法是否是泛型定义True - 方法参数个数2 【构造函数】GenericTestClassInt32 单参构造执行初始值500 【实例方法】泛型方法DateTime执行输入1Int32500输入2DateTime2025/12/16 15:30:00 【子场景2】获取双参数泛型方法GenericInstanceMethodU,V(T, U, V) - 方法参数个数3 【实例方法】泛型方法Single,Guid重载版执行输入1600输入21.23输入3xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx核心说明泛型方法重载的区分核心是 “参数个数 参数类型”方法级泛型参数如 U、V在获取方法时需用object占位绑定泛型参数后再传入具体类型若重载方法的参数类型不同如intvsstring需精准指定参数类型数组避免获取错误方法。四、反射操作泛型的底层原理与性能优化4.1 底层原理泛型类型在 CLR 中是 “模板生成”每个不同的泛型参数绑定如GenericClassint、GenericClassstring会生成独立的 IL 代码反射操作泛型的本质是 “运行时解析泛型元数据”CLR 维护了泛型类型的元数据泛型定义、参数、方法反射 API 通过读取这些元数据实现动态操作MakeGenericType的底层是 “绑定泛型参数到元数据模板生成新的 Type 对象”。4.2 性能优化反射操作的性能远低于静态调用高频场景需优化缓存核心对象缓存Type、MethodInfo、PropertyInfo等对象避免重复调用GetType()/GetMethod()// 示例缓存泛型方法定义 private static readonly MethodInfo _cachedGenericMethod typeof(GenericTestClassint).GetMethod(GenericInstanceMethod);使用 Delegate 减少 Invoke 开销将MethodInfo转换为强类型委托避免每次Invoke的反射开销避免频繁创建实例复用泛型实例减少Activator.CreateInstance的调用使用表达式树Expression替代反射对于高频调用的泛型方法可通过表达式树动态生成委托性能接近静态调用。五、避坑指南常见错误与解决方案常见错误原因解决方案MakeGenericType传入参数个数不匹配泛型定义的形参个数与传入的实参个数不一致如T传 2 个类型检查typeof(类名)的泛型参数个数确保MakeGenericType参数个数匹配Invoke抛出TargetParameterCountException方法参数数组长度与方法定义的参数个数不一致核对方法参数个数确保Invoke的第二个参数数组长度匹配Invoke抛出ArgumentException参数类型与方法定义的参数类型不匹配如 int 传 string确保参数类型与已绑定类型的泛型参数一致GetMethod返回null方法名错误 / 重载匹配失败 / 非公共方法默认 GetMethod 只获取公共方法检查方法名大小写 / 指定参数类型数组 / 使用BindingFlags获取非公共方法泛型接口获取失败接口名未加泛型参数个数如IGenericInterface而非IGenericInterface1使用GetInterface(接口名参数个数 )
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

做钓鱼网站软件网页制作与网站发布

PocketHub离线功能深度解析:随时随地畅享GitHub体验 【免费下载链接】PocketHub PocketHub Android App 项目地址: https://gitcode.com/gh_mirrors/po/PocketHub 在移动互联网时代,网络连接并非总是稳定可靠。PocketHub作为一款优秀的GitHub And…

张小明 2025/12/29 8:51:11 网站建设

北京哪个网站制作公司石家庄最新封闭小区消息

Transformer架构深度剖析:从注意力机制到实战应用 【免费下载链接】NYU-DLSP20 NYU Deep Learning Spring 2020 项目地址: https://gitcode.com/gh_mirrors/pyt/pytorch-Deep-Learning Transformer模型作为深度学习领域的革命性突破,彻底改变了序…

张小明 2025/12/29 8:51:12 网站建设

网站服务器天付网站建设行业背景

Deep-Live-Cam GPU加速实战:从卡顿到流畅的5个关键步骤 【免费下载链接】Deep-Live-Cam real time face swap and one-click video deepfake with only a single image 项目地址: https://gitcode.com/GitHub_Trending/de/Deep-Live-Cam 你是不是经常遇到这样…

张小明 2025/12/29 8:51:15 网站建设

网站开发团队需配备什么岗位广西建设工程协会网站查询

8月28日,腾讯混元实验室正式对外发布重磅开源项目——端到端视频音效生成模型Hunyuan-Foley。这项突破性技术通过融合视觉理解与音频生成能力,首次实现了仅依靠视频画面与文字描述即可自动生成专业级音效的技术跨越,彻底改变了AI视频创作领域…

张小明 2025/12/29 8:51:19 网站建设

网站开发知乎凡科网站建设总结

LangFlow与产品迭代结合:需求收集与优先级排序 在AI产品开发的战场上,最危险的不是技术瓶颈,而是方向错误。一个耗费数月打造的智能客服系统上线后发现用户真正需要的是“自动填写工单”而非“回答常见问题”,这样的故事屡见不鲜。…

张小明 2025/12/29 8:51:17 网站建设

官网的网站建设2345网址导航下载到桌面

当一位中国研究生将精心打磨的中文论文草稿交给某通用AI,要求“翻译并优化为学术英语”后,得到的却是一份令他困惑的结果:专业术语被替换为近似却不够精确的通用词,中文里精妙的四字逻辑概括变成了冗长的从句,全文读起…

张小明 2025/12/30 14:40:01 网站建设