今天在論壇有人問怎樣反射生成數組,突然又來了興致,決定試試
其實反射數組最難無非就是數組的初始化和數組的索引了,那么,如何初始化一個數組呢,數組是沒有構造函數的,那么用InvokeMember(null, BindingFlags.DeclaredOnly |BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.CreateInstance, null, null, new object[] { })
是肯定不行的,用GetMethods來看看,這個類型都有哪些方法。
Type t = Type.GetType("System.Int32[]");
foreach(MethodInfo mi in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
Console.WriteLine(mi.Name);
}
結果如下:

我們看到,有一個名為Set的方法,這個會不會就是呢?
那我們來調用一下看看:
Type t = Type.GetType("System.Int32[]");
int[] array = new int[10];//初始化數組長度為10
array = (int[])(t.InvokeMember("Set", BindingFlags.CreateInstance,null, array, new object[] { 5 }));//這里將它的長度變為5看看是否能成功
Console.WriteLine(array.Length);
可以看到,輸出結果為5,這證明,的確是用Set方法來初始化數組的。
接下來,我們就會想,如何為數組的元素賦值及如何獲取它們的值呢?
再次看一下上面的方法列表,可以看到有GetValue與SetValue方法,那我們來試試:
Type t = Type.GetType("System.Int32[]");
object array = new object();
array = t.InvokeMember("Set", BindingFlags.CreateInstance, null, array, new object[] { 10 });
for (int i = 0; i < 10; i++)
t.GetMethod("SetValue", new Type[2] { typeof(object), typeof(int) }).Invoke(array, new object[] { i, i });
for (int i = 0; i < 10; i++)
Console.WriteLine(t.GetMethod("GetValue", new Type[] { typeof(int) }).Invoke(array, new object[] { i }));
結果如下:

調用成功,其實還是比較簡單的。
可以看到,GetValue與SetValue有多個重載版本,如果想要反射多維數組,就要用到不同的重載,有興趣的朋友可以自己試試。