What is reflection
Reflection objects are used for obtaining type information at runtime. Reflection used to dynamically create an instance of a type, bind the type to an existing object, or invoke its methods or access its fields, properties.
System.Reflection namespace, used to provide the classes which used to access to the metadata of a running program.
Uses of Reflection- Reflection allows to view metadata at runtime.
- Reflection allows to examining various types in an assembly and instantiate these types.
- Reflection allows for late binding to methods and properties.
- Reflection allows to creating new types at runtime.
1) Load assembly at run time and execute methods using Reflection.
System.Reflection namespace, used to provide the classes which used to access to the metadata of a running program
- Assembly assembly = Assembly.LoadFile(@"C:\Calculation.exe");
- Type Ltype = assembly.GetType("CalcReflection.Calc");
-
- object objCalc = Activator.CreateInstance(Ltype);
-
- MethodInfo method1 = Ltype.GetMethod("AddNumbers");
- MethodInfo method2 = Ltype.GetMethod("AddNumber");
-
-
- int result = (int)method1.Invoke(objCalc, null);
- method2.Invoke(objCalc,null);
2) Get meta info at run time using reflection
- Assembly assembly = Assembly.LoadFile(@"C:\Calculation.exe");
- Type[] type = assembly.GetTypes();
- foreach (Type item in type)
- {
- Console.WriteLine("\n\nType Name :"+item.Name+"\n");
- MethodInfo[] method = item.GetMethods();
- Console.WriteLine("\n************ Method Info ***************\n");
- foreach (MethodInfo item1 in method)
- {
- Console.WriteLine("\nMethod Name :"+item1.Name);
- }
- FieldInfo[] field = item.GetFields();
- Console.WriteLine("\n************ Field Info ***************\n");
- foreach (FieldInfo item1 in field)
- {
- Console.WriteLine("\nField Name :" + item1.Name);
- }
- }
That's all. Thanking you. Next time I will come with new topics with example to implement using .Net.