Please login to save your progress.
Introduction to Reflection API
FieldInfo
FieldInfo class discovers the attributes of a field and provides access to field metadata.
To get a list of public fields in an object, we'll use Type's GetFields method:
x
1
Type myObjectType = typeof(MyObject);
2
3
System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields();
The FieldInfo class that gets returned actually contains a lot of useful information. It also contains the ability to set that field on an instance of object- that's where the real power comes in.
Other properties and methods you can check on MSDN
Example
Set instance field values using Reflection API
45
1
using System;
2
3
class MyClass
4
{
5
public string myString;
6
7
public MyClass myInstance;
8
9
public int myInt;
10
}
11
12
public class Program
13
{
14
public static void Main()
15
{
16
Type myType = typeof(MyClass);
17
18
System.Reflection.FieldInfo[] fieldInfo = myType.GetFields();
19
20
MyClass myClass = new MyClass();
21
22
foreach (System.Reflection.FieldInfo info in fieldInfo)
23
{
24
switch (info.Name)
25
{
26
case "myString":
27
info.SetValue(myClass, "string value");
28
break;
29
case "myInt":
30
info.SetValue(myClass, 42);
31
break;
32
case "myInstance":
33
info.SetValue(myClass, myClass);
34
break;
35
}
36
}
37
38
//read back the field information
39
foreach (System.Reflection.FieldInfo info in fieldInfo)
40
{
41
Console.WriteLine(info.Name + ": " +
42
info.GetValue(myClass).ToString());
43
}
44
}
45
}
Page 6 of 11