// Get the type information of a class Type t = typeof(Person); // Get the field information of a field called "age" FieldInfo ageField = t.GetField("age"); // Get the name of the field string fieldName = ageField.Name; // Get the type of the field Type fieldType = ageField.FieldType; // Get the access modifiers of the field bool isPublic = ageField.IsPublic; bool isPrivate = ageField.IsPrivate; bool isProtected = ageField.IsFamily; bool isStatic = ageField.IsStatic; // Get the value of the field for a specific object instance Person p = new Person(); int age = (int)ageField.GetValue(p);
// Get the type information of a class Type t = typeof(Person); // Get all the fields of the class FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); // Loop through each field and print its name and type foreach(FieldInfo field in fields) { Console.WriteLine(field.Name + ": " + field.FieldType); }In this example, we use the `typeof` keyword to get the type information of a class called `Person`. We then use the `GetFields` method with the `BindingFlags.NonPublic` and `BindingFlags.Instance` flags to get all the non-public instance fields of the `Person` class. We can then loop through each field and print out its name and type. The `System.Reflection` package library contains classes and interfaces that provide a way to obtain information about the structure, members, and metadata of .NET types.