Wikipedia says that "In computer science, reflection is the process by which a computer program can view and modify its structure and behavior". C # is a reflection in the work, and when you can not feel it during the runtime, it is capable of checking and changing the information of your application, in which there is a big potential reflection, both of which are normal, the actual The name word reflection capabilities work very well in C #, and it is not difficult to use it in the next few parts, how do we work it and you do something good Examples will look deeper, in which you should be shown how much reflection is useful
However, to take an interest in starting and hoping, here is a small example: It solves a question that I have seen from many new people in any programming language: I only know my name during the sequence How can I change the value of only one variable? Take a look at this small demo application for the solution, and read the next section for an explanation of the various techniques used.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
private static int a = 5, b = 10, c = 20;
static void Main(string[] args)
{
Console.WriteLine("a + b + c = " + (a + b + c));
Console.WriteLine("Please enter the name of the variable that you wish to change:");
string varName = Console.ReadLine();
Type t = typeof(Program);
FieldInfo fieldInfo = t.GetField(varName, BindingFlags.NonPublic | BindingFlags.Static);
if(fieldInfo != null)
{
Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(null) + ". You may enter a new value now:");
string newValue = Console.ReadLine();
int newInt;
if(int.TryParse(newValue, out newInt))
{
fieldInfo.SetValue(null, newInt);
Console.WriteLine("a + b + c = " + (a + b + c));
}
Console.ReadKey();
}
}
}
}
Try running the code and see how it works. Apart from those rows where we use real reflection, it's all very simple. Now, how it works but go to the next section for some more theory.