2012-01-26 59 views
7

這可以動態地創建一個數組:動態創建一個數組並設置元件

Assembly asm = object.GetType().Assembly; 
string sTypeName = "Company.Namespace.ClassName"; 
object arrayWithSize1 = Activator.CreateInstance(asm.GetType(sTypeName), 1); 

但如何設置其上面創建陣列的第一個元素?

回答

12

您可以使用Array.SetValue

// How are you going to create this? Activator.CreateInstance? 
object instance = ... 

// Create one-dimensional array of length 1. 
Array arrayWithSize1 = Array.CreateInstance(asm.GetType(sTypeName), 1); 

// Set first (only) element of the array to the value of instance. 
arrayWithSize1.SetValue(instance, 0); 
7

您可以只使用dynamic關鍵字使代碼比反射更具可讀性呼籲:

var arrayType = typeof(int); 
dynamic array = Array.CreateInstance(arrayType, 1); 
array[0] = 123;