using System;
namespace ReflectionTest
{
public class WriteTest
{
public void WriteString(string s, int i)
{
Console.WriteLine("WriteString:" + s + i);
}
public static void StaticWriteString(string s)
{
Console.WriteLine("StaticWriteString:" + s);
}
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;
Object any = new Object(); // 靜態方法測試用
// 載入組件 (必須絕對路徑)
ass = Assembly.LoadFile(@"D:\Source Code\...\ReflectTest.dll");
type = ass.GetType("ReflectionTest.WriteTest"); // 命名空間+類別名
// 範例 1:實例方法 (有參數)
MethodInfo method = type.GetMethod("WriteString");
Object[] parameters = new Object[] { "test", 1 };
obj = ass.CreateInstance("ReflectionTest.WriteTest"); // 必須實例化
method.Invoke(obj, parameters);
// 範例 2:靜態方法 (有參數)
method = type.GetMethod("StaticWriteString");
method.Invoke(null, new string[] { "test" }); // 第一參數無視
method.Invoke(obj, new string[] { "test" }); // 傳實例也可
method.Invoke(any, new string[] { "test" }); // 傳任意物件也可
// 範例 3:靜態方法 (無參數)
method = type.GetMethod("NoneParaWriteString");
method.Invoke(null, null); // 兩參數皆 null
}
}
| 場景 | CreateInstance | Invoke 第 1 參數 | Invoke 第 2 參數 |
|---|---|---|---|
| 實例方法 | 必要 | 實例 | 參數陣列 |
| 靜態方法 (有參) | 不需要 | 無視 (null/實例/任意) | 參數陣列 |
| 靜態方法 (無參) | 不需要 | null | null |