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