Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. In other words, reflection provides objects that encapsulate assemblies, modules and types. A program reflects on itself by extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior. Reflection is similar to C++ RTTI (Runtime Type Information), but much broader in scope and capability. By using Reflection in C#, one is able to find out details of an object, method, and create objects and invoke methods at runtime. The System.Reflectionnamespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types. When writing a C# code that uses reflection, the coder can use the typeof operator to get the object's type or use the GetType() method to get the type of the current instance. Here are sample codes that demonstrate the use of reflection:
Example:
using System;
using System.Reflection;
public class MyClass
{
public virtual int Add(int numb1,int numb2)
{
int result = numb1 + numb2;
return result;
}
}
class MyMainClass
{
public static int Main()
{
Console.WriteLine ("\nReflection.MethodInfo");
// Create MyClass object
MyClass myClassObj = new MyClass();
// Get the Type information.
Type myTypeObj = myClassObj.GetType("MyClass"); // we can check which type of class is this
// Get Method Information.
MethodInfo myMethodInfo = myTypeObj.GetMethod("Add");
object[] mParam = new object[] {5, 10};
// Get and display the Invoke method.
Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " +
myMethodInfo.Invoke(myClassObj, mParam) + "\n");
return 0;
}
}
We can do many things with reflection. Like we can know if property exists in class, class is abstract o not ? , which method have how many parameters ?, we can decide runtime which method to invoke.
For more visit MSDN : https://msdn.microsoft.com/en-us/library/ms173183.aspx
No comments:
Post a Comment