Sunday, May 22, 2005

Reflection...

For all those who still haven't got their hands dirty with reflection (i was surprised to see a LOT of .NET developers haven't!!) A very good source of learning the basics of reflection is a book called “Applied Microsoft .NET Framework Programming” by Jeffery Ritcher. Here’s a simple ‘Hello World’ of reflection:

To Get My Hands dirty with code I write a simple DLL (Class library project):

using System;
namespace ReflectionDLL
{
public class Sales
{
public Sales() { }
public string SayHello(){return "Hello";}
}
}

This DLL Contains A Module (namespace) named ReflectionDLL, a type(class) named Sales which in turn Contains A Member(function) named SayHello(). The objective is to get this information out of the DLL without looking at it’s source code.

For this I write a windows application which contains the following function:
public void MainFunction()
{
Assembly assem = Assembly.LoadFile("c:\\ReflectionDLL.dll");
foreach(Module m in assem.GetModules())
{
System.Windows.Forms.MessageBox.Show("Showing Modules involved in the DLL: " + m.ToString());
}

foreach(Type t in assem.GetTypes())
{
System.Windows.Forms.MessageBox.Show("Showing Types involved in DLL" + t.ToString());
foreach (MemberInfo m1 in t.GetMembers())
{
System.Windows.Forms.MessageBox.Show("Showing Memebers in current type: " + t.ToString() + " : Member Name is " + m1.ToString());
}
}
}

It’s interesting to note here that besides SayHello member all other framework related members e.g. ToString() (even though we have NOT implemented these) that are present in all objects are also shown.

0 Comments:

Post a Comment

<< Home