gpt4 book ai didi

c# - 动态创建数组并设置元素

转载 作者:太空狗 更新时间:2023-10-29 18:08:39 26 4
gpt4 key购买 nike

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

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);

关于c# - 动态创建数组并设置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9022059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com