Searches for the public field with the specified name.
using System;
using System.Reflection;
public class MyClass
{
public string Field = "A Field";
}
public class MyClass2
{
private string field = "B Field";
public string Field
{
get
{
return field;
}
set
{
if (field!=value)
{
field=value;
}
}
}
}
public class MyFieldInfoClass
{
public static void Main()
{
MyClass2 myFieldObjectB = new MyClass2();
MyClass myFieldObjectA = new MyClass();
Type myTypeA = typeof(MyClass);
FieldInfo myFieldInfo = myTypeA.GetField("Field");
Type myTypeB = typeof(MyClass2);
FieldInfo myFieldInfo1 = myTypeB.GetField("field",
BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("The value of the public field is: '{0}'", myFieldInfo.GetValue(myFieldObjectA));
Console.WriteLine("The value of the private field is: '{0}'",myFieldInfo1.GetValue(myFieldObjectB));
}
}
Related examples in the same category