Description
Refelction is the mechanism of discovering class information solely at run time.Wondering where it would be useful? Imagine,you are in visual studio IDE (Integrated devolopment environment) and as you type "object." you would see all the methods,properties and events associated with that object.An other example would be an Object browser.The code attached here,loads all assemblies and displays each class,its contructors, methods, properties and events in tree view.The form also hase a command botton (labeled More Reflection) in whose click event I create an object of MyClass1 class based on the name of the class and invoke its methods during run time.Here is an explanation of the code with information on various classes and methods used.
I have called the name space MyReflection.Then I have declared MyClass1 and MyClass2 which are used in the click event of More reflection Button.I will talk about these classes when I come to the click event of this button.Next,I have called my form as TestReflection and is inherited from System.Winforms.Form.Most of the assemblies are found in D:\\WINNT\\Microsoft.NET\\Framework\\v1.0.2204\\.If this is not the path in your computer change it to appropriate path on your computer.I have stored all the paths of the assemblies in an array called arAssemblyPath.I have used System.Winforms.dll and System.dll and commented the rest, to speed up loading and unloading of application.I have declared an array of Types ,arOfTypes to store all the s from an assembly.I have a for loop that loads each assembly and gets its types.To do this I had to use Assembly class in System.Reflection name space.Let us talk a little bit about this class before we move on.
System.Reflection.Assembly:
It defines an assembly which is a reusable,versionable and self describing building block of a Common Language Run time application.I will discuss here only the functions that I have used in my code.
objAssembly=System.Reflection.Assembly.LoadFrom(str);
LoadFrom function takes the path of the assembly to load and loads it and returns that Assembly.
After loading the assembly we want to get all the types in that assembly.This class provides a function GetTypes() (It returns an array of System.Type objects in that assembly) which will do that for us and that line for the code is.
arOfTypes=objAssembly.GetTypes();
Now having touched System.Type class,Let us talk about it.
System.Type:
This class represents type declarations.(class types, interface types, array types, value types and enumeration types.)
It is the root of all Reflection operations.It is the primary means by which we access metadata and it acts as a Gateway to Reflection API.It provides methods for obtaining information about a Type declaration, such as the constructors, properties, methods and Events.
Extracting Constructor Information: