FieldHandle
In this chapter you will learn:
Get FieldHandle
FieldInfo.FieldHandle
Property gets a RuntimeFieldHandle
,
which is a handle to the internal metadata representation of a field.
using System;//jav a 2s .c om
using System.Reflection;
public class MyClass
{
public string MyField = "Microsoft";
}
public class FieldInfo_FieldHandle
{
public static void Main()
{
MyClass myClass =new MyClass();
Type myType = typeof(MyClass);
try
{
FieldInfo myFieldInfo = myType.GetField("MyField", BindingFlags.Public | BindingFlags.Instance);
if(myFieldInfo!=null)
{
RuntimeFieldHandle myFieldHandle=myFieldInfo.FieldHandle;
DisplayFieldHandle(myFieldHandle);
}
else
{
Console.WriteLine("The myFieldInfo object is null.");
}
}
catch(Exception e)
{
Console.WriteLine("Exception: {0}", e.Message);
}
}
public static void DisplayFieldHandle(RuntimeFieldHandle myFieldHandle)
{
FieldInfo myField = FieldInfo.GetFieldFromHandle(myFieldHandle);
Console.WriteLine("The type is {0}.", myField.ToString());
}
}
Get Field From Field Handle
FieldInfo.GetFieldFromHandle
Method gets
a FieldInfo for the field represented by the specified handle.
using System;//from j a v a2s.c om
using System.Reflection;
public class MainClass
{
public string x;
public char y;
public float a;
public int b;
public static void Main()
{
Type myType = typeof(MainClass);
FieldInfo [] myFieldInfoArray = myType.GetFields();
RuntimeFieldHandle myRuntimeFieldHandle;
for(int i = 0; i < myFieldInfoArray.Length; i++)
{
myRuntimeFieldHandle = myFieldInfoArray[i].FieldHandle;
FieldInfo myFieldInfo = FieldInfo.GetFieldFromHandle(myRuntimeFieldHandle);
Console.WriteLine("{0}", myFieldInfo);
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Reflection