Mega Code Archive

 
Categories / C# / Reflection
 

Gets a FieldInfo for the field represented by the specified handle, for the specified generic type

using System; using System.Reflection; public class Test<T> {     public T TestField; } public class Example {     public static void Main()     {         RuntimeTypeHandle rth = typeof(Test<string>).TypeHandle;         RuntimeFieldHandle rfh = typeof(Test<string>).GetField("TestField").FieldHandle;         try         {             FieldInfo f1 = FieldInfo.GetFieldFromHandle(rfh);         }         catch(Exception ex)         {             Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);         }         FieldInfo fi = FieldInfo.GetFieldFromHandle(rfh, rth);         Console.WriteLine("\r\nThe type of {0} is: {1}", fi.Name, fi.FieldType);         fi = FieldInfo.GetFieldFromHandle(rfh, typeof(Test<object>).TypeHandle);         Console.WriteLine("\r\nThe type of {0} is: {1}", fi.Name, fi.FieldType);         try         {             fi = FieldInfo.GetFieldFromHandle(rfh, typeof(Test<int>).TypeHandle);         }         catch(Exception ex)         {             Console.WriteLine("\r\n{0}: {1}", ex.GetType().Name, ex.Message);         }     } }