The purpose of this article is to describe some of the practical uses of the Reflection.
Introduction
The purpose of this article is to describe some of the practical uses of the
Reflection.
Reflection
Reflection is an important resource of the Microsoft Framework, for example,
enables us to get some information about object in runtime, in this article
we will iterate thought all properties of a class named Person, using Reflection.
Person is a simple class, used just to hold information about a Person.
The following C# .Net code shows how to do it.
Example Code
class Program
{
static void Main(string[] args)
{
Person oPerson = new Person();
oPerson.iAge = 27;
oPerson.sName = "Fernando Vezzali";
PropertyInfo[] properties = oPerson.GetType().GetProperties();
foreach (PropertyInfo oPropertyInfo in properties)
{
MethodInfo oMethodInfo = oPerson.GetType().GetMethod("get_" + oPropertyInfo.Name);
ParameterInfo[] ArrParameterInfo = oPerson.GetType().GetMethod("get_" + oPropertyInfo.Name).GetParameters();
Console.WriteLine(oPropertyInfo.Name + " = " + oMethodInfo.Invoke(oPerson, ArrParameterInfo));
}
Console.Read();
}
}
class Person
{
private int _iAge;
private string _sName;
public int iAge
{
get { return _iAge; }
set { _iAge = value; }
}
public string sName
{
get { return _sName; }
set { _sName = value; }
}
}
Conclusion
The Person class extends object and does not implement any interface.
Using reflection we can iterate thought all properties.