• net core 反射获取泛型-泛型方法method<T>(T t1)


    参考微软说明: How to: Examine and Instantiate Generic Types with Reflection - .NET Framework | Microsoft Learn

    目标方法

    1. public class GenericTest
    2. {
    3. public Dictionary<string, string> TestGeneric<T1, T2>(T1 t1, T2 t2)
    4. where T1 : TestBase, ITestArgument where T2 : class, new()
    5. {
    6. return null;
    7. }
    8. }

    //判断逻辑

    1. var testType = typeof(GenericTest);
    2. var methods = testType.GetMethods();
    3. //获取泛型方法
    4. var genericMethod = methods[0];
    5. //判断是否是泛型
    6. if (!genericMethod.IsGenericMethod)
    7. {
    8. return;
    9. }
    10. //获取泛型信息
    11. var genericArgs = genericMethod.GetGenericArguments();
    12. //获取泛型T1
    13. var arg1 = genericArgs[0];
    14. //获取T1名称
    15. var name = arg1.Name;
    16. //获取约束 T1约束, where T1: TestBase, ITestArgument
    17. var arg1constraints = arg1.GetGenericParameterConstraints();
    18. foreach (Type iConstraint in arg1constraints)
    19. {
    20. if (iConstraint.IsInterface)
    21. {
    22. //ITestArgument
    23. var itestArgumentName = iConstraint.Name;
    24. }
    25. else
    26. {
    27. //TestBase
    28. var testBaseName = iConstraint.Name;
    29. }
    30. }
    31. //获取T2约束 where T2 : class, new()
    32. var arg2 = genericArgs[1];
    33. GenericParameterAttributes arg2Constraints =
    34. arg2.GenericParameterAttributes &
    35. GenericParameterAttributes.SpecialConstraintMask;
    36. if (arg2Constraints != GenericParameterAttributes.None)
    37. {
    38. if (GenericParameterAttributes.None != (arg2Constraints &
    39. GenericParameterAttributes.DefaultConstructorConstraint))
    40. {
    41. //包含 new()
    42. }
    43. if (GenericParameterAttributes.None != (arg2Constraints &
    44. GenericParameterAttributes.ReferenceTypeConstraint))
    45. {
    46. //包含 class
    47. }
    48. if (GenericParameterAttributes.None != (arg2Constraints &
    49. GenericParameterAttributes.NotNullableValueTypeConstraint))
    50. {
    51. //包含 notnull
    52. }
    53. }

    官网示例代码

    1. using System;
    2. using System.Reflection;
    3. using System.Collections.Generic;
    4. // Define an example interface.
    5. public interface ITestArgument {}
    6. // Define an example base class.
    7. public class TestBase {}
    8. // Define a generic class with one parameter. The parameter
    9. // has three constraints: It must inherit TestBase, it must
    10. // implement ITestArgument, and it must have a parameterless
    11. // constructor.
    12. public class Test<T> where T : TestBase, ITestArgument, new() {}
    13. // Define a class that meets the constraints on the type
    14. // parameter of class Test.
    15. public class TestArgument : TestBase, ITestArgument
    16. {
    17. public TestArgument() {}
    18. }
    19. public class Example
    20. {
    21. // The following method displays information about a generic
    22. // type.
    23. private static void DisplayGenericType(Type t)
    24. {
    25. Console.WriteLine("\r\n {0}", t);
    26. Console.WriteLine(" Is this a generic type? {0}",
    27. t.IsGenericType);
    28. Console.WriteLine(" Is this a generic type definition? {0}",
    29. t.IsGenericTypeDefinition);
    30. // Get the generic type parameters or type arguments.
    31. Type[] typeParameters = t.GetGenericArguments();
    32. Console.WriteLine(" List {0} type arguments:",
    33. typeParameters.Length);
    34. foreach( Type tParam in typeParameters )
    35. {
    36. if (tParam.IsGenericParameter)
    37. {
    38. DisplayGenericParameter(tParam);
    39. }
    40. else
    41. {
    42. Console.WriteLine(" Type argument: {0}",
    43. tParam);
    44. }
    45. }
    46. }
    47. // The following method displays information about a generic
    48. // type parameter. Generic type parameters are represented by
    49. // instances of System.Type, just like ordinary types.
    50. private static void DisplayGenericParameter(Type tp)
    51. {
    52. Console.WriteLine(" Type parameter: {0} position {1}",
    53. tp.Name, tp.GenericParameterPosition);
    54. Type classConstraint = null;
    55. foreach(Type iConstraint in tp.GetGenericParameterConstraints())
    56. {
    57. if (iConstraint.IsInterface)
    58. {
    59. Console.WriteLine(" Interface constraint: {0}",
    60. iConstraint);
    61. }
    62. }
    63. if (classConstraint != null)
    64. {
    65. Console.WriteLine(" Base type constraint: {0}",
    66. tp.BaseType);
    67. }
    68. else
    69. {
    70. Console.WriteLine(" Base type constraint: None");
    71. }
    72. GenericParameterAttributes sConstraints =
    73. tp.GenericParameterAttributes &
    74. GenericParameterAttributes.SpecialConstraintMask;
    75. if (sConstraints == GenericParameterAttributes.None)
    76. {
    77. Console.WriteLine(" No special constraints.");
    78. }
    79. else
    80. {
    81. if (GenericParameterAttributes.None != (sConstraints &
    82. GenericParameterAttributes.DefaultConstructorConstraint))
    83. {
    84. Console.WriteLine(" Must have a parameterless constructor.");
    85. }
    86. if (GenericParameterAttributes.None != (sConstraints &
    87. GenericParameterAttributes.ReferenceTypeConstraint))
    88. {
    89. Console.WriteLine(" Must be a reference type.");
    90. }
    91. if (GenericParameterAttributes.None != (sConstraints &
    92. GenericParameterAttributes.NotNullableValueTypeConstraint))
    93. {
    94. Console.WriteLine(" Must be a non-nullable value type.");
    95. }
    96. }
    97. }
    98. public static void Main()
    99. {
    100. // Two ways to get a Type object that represents the generic
    101. // type definition of the Dictionary class.
    102. //
    103. // Use the typeof operator to create the generic type
    104. // definition directly. To specify the generic type definition,
    105. // omit the type arguments but retain the comma that separates
    106. // them.
    107. Type d1 = typeof(Dictionary<,>);
    108. // You can also obtain the generic type definition from a
    109. // constructed class. In this case, the constructed class
    110. // is a dictionary of Example objects, with String keys.
    111. Dictionary<string, Example> d2 = new Dictionary<string, Example>();
    112. // Get a Type object that represents the constructed type,
    113. // and from that get the generic type definition. The
    114. // variables d1 and d4 contain the same type.
    115. Type d3 = d2.GetType();
    116. Type d4 = d3.GetGenericTypeDefinition();
    117. // Display information for the generic type definition, and
    118. // for the constructed type Dictionary.
    119. DisplayGenericType(d1);
    120. DisplayGenericType(d2.GetType());
    121. // Construct an array of type arguments to substitute for
    122. // the type parameters of the generic Dictionary class.
    123. // The array must contain the correct number of types, in
    124. // the same order that they appear in the type parameter
    125. // list of Dictionary. The key (first type parameter)
    126. // is of type string, and the type to be contained in the
    127. // dictionary is Example.
    128. Type[] typeArgs = {typeof(string), typeof(Example)};
    129. // Construct the type Dictionary.
    130. Type constructed = d1.MakeGenericType(typeArgs);
    131. DisplayGenericType(constructed);
    132. object o = Activator.CreateInstance(constructed);
    133. Console.WriteLine("\r\nCompare types obtained by different methods:");
    134. Console.WriteLine(" Are the constructed types equal? {0}",
    135. (d2.GetType()==constructed));
    136. Console.WriteLine(" Are the generic definitions equal? {0}",
    137. (d1==constructed.GetGenericTypeDefinition()));
    138. // Demonstrate the DisplayGenericType and
    139. // DisplayGenericParameter methods with the Test class
    140. // defined above. This shows base, interface, and special
    141. // constraints.
    142. DisplayGenericType(typeof(Test<>));
    143. }
    144. }

  • 相关阅读:
    【高级网络程序设计】Mid-Term Test
    轻量封装WebGPU渲染系统示例<4>-CubeMap/天空盒(源码)
    NIM游戏/SG函数
    防火墙---双机热备技术
    AI美颜SDK算法详解
    项目中字符串判空总结
    mysql的索引分类
    请写出一个高效的在m*n矩阵中判断目标值是否存在的算法
    JAVA-JDK镜像下载地址
    Cesium源码编译使用(weixin公众号【图说GIS】)
  • 原文地址:https://blog.csdn.net/pehao/article/details/133712747