Getting Started with C # reflection first understand that C # reflection provides an object that encapsulates assemblies, modules, and types, and so on. So you can use reflection to dynamically create an instance of a type, bind a type to an existing object, or get a type from an existing object and call its methods or access its fields and properties. If you use attributes in your code, you can use reflection to access them.
One of the simplest examples of C # reflection, first write the class library as follows:
using System;
namespace ReflectionTest
{
public class WriteTest
{
//public method with parametors
public void WriteString(string s, int i)
{
Console.WriteLine("WriteString:" + s + i.ToString());
}
//static method with only one parametor
public static void StaticWriteString(string s)
{
Console.WriteLine("StaticWriteString:" + s);
}
//static method with no parametor
public static void NoneParaWriteString()
{
Console.WriteLine("NoParaWriteString");
}
}
}
Compile with the command line compile csc/t:library ReflectTest.cs command to generate the ReflectTest.dll library file.
The following procedures are then written:
using System;
using System.Reflection;
Class TESTAPP
{
public static void Main ()
{
Assembly ass;
Type type;
Object obj;
//used to test the static method
Object any = new object ();
//load The DLL
//must indicates the whole path of dll
Ass = assembly.loadfile (@ "D:\Source code\00.c#
Sudy \01.reflection\01\reflecttest.dll ");
//must is Namespace with class name
Type = Ass. GetType ("Reflectiontest.writetest");
/**//*example1---------*/
MethodInfo method = type. GetMethod ("WriteString");
String test = "Test";
int i = 1;
object[] parametors = new Object[]{test,i};
//since The Writetest class is not Static your should Create the instance of this class
obj = Ass. CreateInstance ("Reflectiontest.writetest");
Method. Invoke (
Obj,//instance object of the class need to is reflect
Parametors)//parametors of indicated method
//method. Invoke (anY, parametors);//runtimeerror:class reference is wrong
/**//*example2----------*/
method = type. GetMethod ("staticwritestring");
//the The Parametor is ignored
method. Invoke (NULL, new string[] {"Test"});
method. Invoke (obj, new string[] {"Test"});//indicates the instance would equals above line
method. Invoke (Any, new string[] {"Test"});//even the class reference is wrong
/**//*example3-----------*/
Meth OD = type. GetMethod ("noneparawritestring");
//sine The noneparawritestring ()
has no parametors so does not indicate any parametors
method. Invoke (null, NULL);
}
}