A FieldInfo class provides detailed information about a single field of a class or an interface. The reflected field may be a static field or an instance field. The FieldInfoSpy example shows how to obtain the field information of a class including the access modifiers, type etc:
using System;
using System.Reflection;
namespace ConsoleApplication1
{
internal class FieldInfoSpy
{
private static void Main(string[] args)
{
Type type = typeof (Car);
//query type
FieldInfo[] fieldInfos = type.GetFields(
//Specifies that instance members are to be included in the search.
BindingFlags.Instance |
//Specifies that non-public members are to be included in the search.
BindingFlags.NonPublic |
//Specifies that public members are to be included in the search.
BindingFlags.Public |
//Specifies that static members are to be included in the search.
BindingFlags.Static);
foreach (FieldInfo fieldInfo in fieldInfos)
{
Console.WriteLine(
"Name:{0},Type:{1},Public:{2},Static:{3},Readonly:{4}",
fieldInfo.Name,
fieldInfo.FieldType.FullName,
fieldInfo.IsPublic,
fieldInfo.IsStatic,
fieldInfo.IsInitOnly
);
}
Console.ReadLine();
}
}
internal class Car
{
public bool broken;
private static string vendor;
public readonly string owner;
private int age;
protected string name;
}
}
A sample of the output follows:
Name:broken,Type:System.Boolean,Public:True,Static:False,Readonly:False
Name:owner,Type:System.String,Public:True,Static:False,Readonly:True
Name:age,Type:System.Int32,Public:False,Static:False,Readonly:False
Name:name,Type:System.String,Public:False,Static:False,Readonly:False
Name:vendor,Type:System.String,Public:False,Static:True,Readonly:False