反射的簡單應用
作者 jlgzw
使用反射在運作時建立類型執行個體,并調用和通路這些執行個體。
//--------------------------------------------------------------------------------------------------------------
// ReflectType.cs @ 2007 by jl gzw
//--------------------------------------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ReflectType
{
static class ReflectType
{
static void Main()
{
//使用string類型
Type type = typeof(string);
//string類構造函數參數類型
Type[] aTypes = new Type[] { typeof(char),typeof(int) };
//string類構造函數參數
object[] aParams = new object[] { 'c', 10 };
object Obj = null;
ConstructorInfo myctor = type.GetConstructor(aTypes);
Obj = myctor.Invoke(aParams);
Console.WriteLine("構造了字元串: {0}",Obj);
object[] Arg = {Obj ,"這是一個連接配接字元串"};
object str = type.InvokeMember("Concat", BindingFlags.InvokeMethod, null,null,Arg);
Console.WriteLine("使用string.Concat方法連接配接後的字元串: {0}",str);
Console.Read();
}
}
}