C#反射的入門學習首先要明白C#反射提供了封裝程序集、模塊和類型的對象等等。那麼這樣可以使用反射動態創建類型的實例,將類型綁定到現有對象,或從現有對象獲取類型並調用其方法或訪問其字段和屬性。如果代碼中使用了屬性,可以利用反射對它們進行訪問。
一個最簡單的C#反射實例,首先編寫類庫如下:
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");
}
}
}
使用命令行編譯csc /t:library ReflectTest.cs命令進行編譯,生成ReflectTest.dll庫文件。
然後進行下列程序的編寫:
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 be 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 you should Create the instance of this class
obj = ass.CreateInstance("ReflectionTest.WriteTest");
method.Invoke(
obj,//Instance object of the class need to be reflect
parametors);//Parametors of indicated method
//method.Invoke(any, parametors);//RuntimeError: class reference is wrong
/**//*example2----------*/
method = type.GetMethod("StaticWriteString");
//The first parametor will be ignored
method.Invoke(null, new string[] { "test"});
method.Invoke(obj, new string[] { "test"});//indicates the instance will equals above line
method.Invoke(any, new string[] { "test"});//Even the class reference is wrong
/**//*example3-----------*/
method = type.GetMethod("NoneParaWriteString");
//Sine the method NoneParaWriteString()
has no parametors so do not indicate any parametors
method.Invoke(null, null);
}
}