Long time did not review the reflection of knowledge, today to explain the general second use of reflection.
two. Reflection on methods, properties, etc.
You first need to write a test class that generates an. exe or. dll file.
Class Test
{public Test ()//General construction method
{ }
public string WriteString (string s)//argument method
{return "Welcome:" + S; }
public static string staticstring (string s)//static method
{return "Welcome:" + S; }
public string Writestringno ()//No parameter method
{return "Welcome:chen"; }}
Locate the. exe file, which can be temporarily replicated on the desktop for easy searching.
The general invocation of the test class method, using the creation of an object and instantiation to refer to the method, such as:
Test t=new test ();
T.writestring ();
Reflection invocation (calls between two items):
Then create a ConsoleApplication2 console program.
Refer to namespaces using System.Reflection first;
ConsoleApplication2:
Using reflection
static void Main (string[] args)
{
Assembly ass;//Assembly
Type ty;//equivalent to class
Object ob;//is equivalent to objects
string path = @ "C:\Users\Shuang\Desktop\ConsoleApplication1.exe";//assembly path
Assembly.loadfile (path);//Loading assembly
Ty = the. GetType ("Consoleapplication1.test");//Get the Test class name; Format: "Namespace. Class Name"
MethodInfo meth = ty. GetMethod ("writestring");//Get method, Format: "Method name" parameter
MethodInfo meth1 = ty. GetMethod ("Writestringno");//Get method, Format: "Method name" no parameter
MethodInfo meth2 = ty. GetMethod ("staticstring");//Get method, Format: "Method name" static
OB = the. CreateInstance ("Consoleapplication1.test");//Create an object in the format: "namespace. Class Name"
String[] Canshu = {"Chen1"};//parameter array
string res = (string) meth. Invoke (Ob,canshu);//get result; Format: object, parameter (parameter is an object array) parameter
String res1 = (string) meth1. Invoke (ob, NULL);//get result; Format: object, parameter (parameter is an object array) no arguments
String res2 = (string) meth2. Invoke (null, Canshu);///get result; Format: object, parameter (parameter is an object array) static
Console.Write ("Ginseng:" +res+ "\ n");
Console.Write ("No reference:" + res1 + "\ n");
Console.Write ("Static:" + Res2);
Console.ReadLine ();
}
C # Reflection (ii)