Assembly information that can be accessed or manipulated includes type, properties, methods, events of object, constructors etc.
Reflection allows to access information at runtime of assembly that is not available at compile time.
Reflection uses PE file of assembly to access assembly information.
Name spaces those provide required classes
1. System.Reflection
2. System.Type
objAssembly=System.Reflection.Assembly.LoadFrom(str path);
After loading assembly you can get all types from assembly, Function GetTypes() returns array of objects of System.Type
arOfTypes=objAssembly.GetTypes();
Some functions to get information of an object of System.Type
ConstructorInfo[] ctrInfo=t.GetConstructors(); //Returns array of objects of ConstructorInfo type
PropertyInfo[] pInfo = t.GetProperties(); //Returns array of objects of PropertyInfo type
MethodInfo[] mInfo=t.GetMethods(); //Returns array of objects of MethodInfo type
EventInfo[] eInfo=t.GetEvents(); //Returns array of objects of EventInfo type
Type t= Type.GetType("MyReflection.MyClass1"); //Returns object of type MyClass1.
=============
Getting all types information that assembly have
Code block 1
using System.Reflection;
class Class1
{
public static void Main()
{ // You must supply a valid fully qualified assembly name.
Assembly SampleAssembly = Assembly.Load
("SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken = 8744b20f8da049e3");
// Display all the types contained in the specified assembly.
foreach (Type oType in SampleAssembly.GetTypes())
{
Console.WriteLine(oType.Name);
}
}
}
Getting complete information of a method using loadfrom method
Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("c:\\Sample.Assembly.dll");
// Obtain a reference to a method known to exist in assembly.
MethodInfo Method = SampleAssembly.GetTypes()[0].GetMethod("Method1");
// Obtain a reference to the parameters collection of the MethodInfo instance.
ParameterInfo[] Params = Method.GetParameters();
// Display information about method parameters.
// Param = sParam1
// Type = System.String
// Position = 0
// Optional=False
foreach (ParameterInfo Param in Params)
{
Console.WriteLine("Param=" + Param.Name.ToString());
Console.WriteLine(" Type=" + Param.ParameterType.ToString());
Console.WriteLine(" Position=" + Param.Position.ToString());
Console.WriteLine(" Optional=" + Param.IsOptional.ToString());
}
Type[] objType = objAsmbl.GetTypes();
foreach (Type type in objType)
{
MethodInfo[] lstMethods = type.GetMethods();
EventInfo[] lstEvents = type.GetEvents();
ConstructorInfo[] lstConstructor = type.GetConstructors();
FieldInfo[] lstFields = type.GetFields();
foreach (MethodInfo mthd in lstMethods)
{
Console.WriteLine(mthd.Name + mthd.ReturnType.ToString() + mthd.IsStatic.ToString());
ParameterInfo[] lstParameter = mthd.GetParameters();
foreach (ParameterInfo pi in lstParameter)
{
Console.WriteLine(pi.Name + pi.ParameterType.ToString() + pi.Position.ToString() + pi.IsOptional.ToString());
}
}
}
