gpt4 book ai didi

c# - 如何将 object[] 转换为更具体类型的数组

转载 作者:可可西里 更新时间:2023-11-01 03:14:00 25 4
gpt4 key购买 nike

如果我在编译时知道类型或者它是一个通用参数,这将非常简单,因为我可以做类似 myArray.Cast<T>() 的事情但我实际上拥有的基本上是这个。我没有已知类型或通用参数。我有一个 System.Type变量。

// could actually be anything else
Type myType = typeof(string);

// i already know all the elements are the correct types
object[] myArray = new object[] { "foo", "bar" };

我可以使用某种反射魔法来获得 string[] 吗?包含相同数据的引用? (其中 string 在编译时未知)

最佳答案

这并不是真正的强制转换(我正在分配一个新数组并复制原始数组),但这也许可以帮助您?

Type myType = typeof(string);
object[] myArray = new object[] { "foo", "bar" };

Array destinationArray = Array.CreateInstance(myType, myArray.Length);
Array.Copy(myArray, destinationArray, myArray.Length);

在此代码中,destinationArray 将是 string[] 的一个实例(或者是 myType 的任何类型的数组)。

关于c# - 如何将 object[] 转换为更具体类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6470554/

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