这可以动态创建一个数组:
Assembly asm = object.GetType().Assembly;
string sTypeName = "Company.Namespace.ClassName";
object arrayWithSize1 = Activator.CreateInstance( asm.GetType(sTypeName), 1 );
但是如何设置上面创建的数组的第一个元素呢?
您可以使用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);
您只需使用dynamic
关键字即可使代码比反射调用更具可读性:
var arrayType = typeof(int);
dynamic array = Array.CreateInstance(arrayType, 1);
array[0] = 123;