How to iterate thought all properties of a class
The purpose of this article is to describe some of the practical uses of the Reflection.
Reflection is an important resource of the .NET Framework and enables us to get information about objects at runtime. In this article we will iterate thought all of the properties of a class named Person using Reflection.
The Person class extends object and does not implement any interface. It is a simple class used just to hold information about a Person.
The following C# .NET code shows how to do it. (or download the solution: http://weblogs.asp.net/blogs/fernandovezzali/ReflectionProject.zip)
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; }
}
}
Revision number 2, Sunday, September 07, 2008 8:51:48 PM by mbanavige
You must Login to comment.
|
Tue, Sep 9, 2008 5:47 AM
by cliquerz
|
This is cool. Two thumbs up!
|
|
Sun, Oct 26, 2008 9:49 PM
by joechung
|
What does this have to do with ASP.NET?
|
|
Mon, Oct 27, 2008 6:18 PM
by mbanavige
|
@joechung: While the example in this article currently uses a console app for demonstration purposes, reflection is still an applicable (and powerful) technique that can be used in ASP.NET web apps.
|