Answers for "Reflection: Using FieldInfo"

C#
0

Reflection: Using 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:

Type myObjectType = typeof(MyObject);

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.

//Example
//Set instance field values using Reflection API

using System;

class MyClass
{
	public string myString;	
	public MyClass myInstance;	
	public int myInt;
}
					
public class Program
{
	public static void Main()
	{
		Type myType = typeof(MyClass);
		System.Reflection.FieldInfo[] fieldInfo = myType.GetFields();		
		MyClass myClass = new MyClass();
		foreach (System.Reflection.FieldInfo info in fieldInfo)
		{
		   switch (info.Name)
		   {
			  case "myString":
				 info.SetValue(myClass, "string value");
				 break;
			  case "myInt":
				 info.SetValue(myClass, 42);
				 break;
			  case "myInstance":
				 info.SetValue(myClass, myClass);
				 break;
		   }
		}
		
		//read back the field information
		foreach (System.Reflection.FieldInfo info in fieldInfo)
		{
		   Console.WriteLine(info.Name + ": " + 
			  info.GetValue(myClass).ToString());
		}
	}
}

//Output
myString: string value
myInstance: MyClass
myInt: 42
Posted by: Guest on August-27-2021

Code answers related to "Reflection: Using FieldInfo"

C# Answers by Framework

Browse Popular Code Answers by Language