24 Mayıs 2012 Perşembe

C# Reflection Field Example


You have a class with instance or static fields of any type in your C# program and want to loop through those fields and display their names and values. The System.Reflection namespace in the .NET Framework provides a powerful and maintainable way to enumerate fields and properties. We see how you can loop through fields using reflection.

Example

In the .NET Framework, every program is compiled into an assembly containing metadata, which is an abstract binary representation of the program's structure. This improves the options you have when executing your program, as you can explore the string data stored in the executable to access field and property names.
This example demonstrates a static class with four fields of type Int32 and String. It obtains the FieldInfo objects for those fields and then displays them in a public method.

This C# example program uses reflection on fields in a static class.
Program that uses reflection on fields [C#]

using System;
using System.Reflection;

static class ReflectionTest
{
    public static int Height;
    public static int Width;
    public static int Weight;
    public static string Name;

    public static void Write()
    {
 Type type = typeof(ReflectionTest); // Get type pointer
 FieldInfo[] fields = type.GetFields(); // Obtain all fields
 foreach (var field in fields) // Loop through fields
 {
     string name = field.Name; // Get string name
     object temp = field.GetValue(null); // Get value
     if (temp is int) // See if it is an integer.
     {
  int value = (int)temp;
  Console.Write(name);
  Console.Write(" (int) = ");
  Console.WriteLine(value);
     }
     else if (temp is string) // See if it is a string.
     {
  string value = temp as string;
  Console.Write(name);
  Console.Write(" (string) = ");
  Console.WriteLine(value);
     }
 }
    }
}

class Program
{
    static void Main()
    {
 ReflectionTest.Height = 100; // Set value
 ReflectionTest.Width = 50; // Set value
 ReflectionTest.Weight = 300; // Set value
 ReflectionTest.Name = "Perl"; // Set value
 ReflectionTest.Write(); // Invoke reflection methods
    }
}

Output

Height (int) = 100
Width (int) = 50
Weight (int) = 300
Name (string) = Perl