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

我們看到,有一個(gè)名為Set的方法,這個(gè)會(huì)不會(huì)就是呢?
那我們來(lái)調(diào)用一下看看:
Type t = Type.GetType("System.Int32[]");
int[] array = new int[10];//初始化數(shù)組長(zhǎng)度為10
array = (int[])(t.InvokeMember("Set", BindingFlags.CreateInstance,null, array, new object[] { 5 }));//這里將它的長(zhǎng)度變?yōu)?看看是否能成功
Console.WriteLine(array.Length);
可以看到,輸出結(jié)果為5,這證明,的確是用Set方法來(lái)初始化數(shù)組的。
接下來(lái),我們就會(huì)想,如何為數(shù)組的元素賦值及如何獲取它們的值呢?
再次看一下上面的方法列表,可以看到有GetValue與SetValue方法,那我們來(lái)試試:
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 }));
結(jié)果如下:

調(diào)用成功,其實(shí)還是比較簡(jiǎn)單的。
可以看到,GetValue與SetValue有多個(gè)重載版本,如果想要反射多維數(shù)組,就要用到不同的重載,有興趣的朋友可以自己試試。