Mega Code Archive

 
Categories / C# / Reflection
 

Gets a MethodBase that represents the declaring method, if the current Type represents a type parameter of a generic method

using System; using System.Reflection; public class Example {     public static void Generic<T>(T toDisplay)     {         Console.WriteLine("\r\nHere it is: {0}", toDisplay);     } } public class Test {     public static void Main()     {         Type ex = typeof(Example);         MethodInfo mi = ex.GetMethod("Generic");         DisplayGenericMethodInfo(mi);     }     private static void DisplayGenericMethodInfo(MethodInfo mi)     {         Console.WriteLine("", mi);         Console.WriteLine("Is this a generic method definition? {0}", mi.IsGenericMethodDefinition);         Console.WriteLine("Is it a generic method? {0}", mi.IsGenericMethod);         Console.WriteLine("Does it have unassigned generic parameters? {0}", mi.ContainsGenericParameters);         if (mi.IsGenericMethod)         {             Type[] typeArguments = mi.GetGenericArguments();             Console.WriteLine("List type arguments ({0}):", typeArguments.Length);             foreach (Type tParam in typeArguments)             {                 if (tParam.IsGenericParameter){                     Console.WriteLine("{0}  parameter position {1}" +                         "\n declaring method: {2}",                         tParam,                         tParam.GenericParameterPosition,                         tParam.DeclaringMethod);                 }                 else                 {                     Console.WriteLine("\t\t{0}", tParam);                 }             }         }     } }