动态创建数组并设置元素

时间:2012-01-26 17:01:11

标签: c# arrays reflection activator createinstance

这可以动态创建一个数组:

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

但是如何设置上面创建的数组的第一个元素?

2 个答案:

答案 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;