Skip to main content
 首页 » 编程设计

c#之在运行时将对象转换为字符串数组

2024年02月05日25shihaiming

我的代码中有一行:

var objects = ExternalApiGetObjects(....); 

在开发时我只知道 ExternalApiGetObjects返回 Object实例。事实上,我确定 objects变量是某种类型的数组。 我想通过objects变量为 String.Join方法,但在运行时我遇到了类似这样的异常:“类型为‘System.Int32[]’的对象无法转换为类型‘System.String[]’。”

在大多数情况下,objects不会是字符串数组。它可以是一个 int 数组,甚至是某个用户类型的数组。我只知道对象是一个数组,我想调用 ToString()在该数组的每个项目上创建一个类型为 string[] 的新项目.

如何转换我的 objects至 string[] ?

请您参考如下方法:

OP: It could be an int array, or even an array of some user's type. I just know that objects is an array and I want to invoke ToString() on each item of that array to create a new one with type of string[]

您可以将其转换为 IEnumerable , 然后使用 Cast<T> 将元素转换为对象,然后选择元素。例如:

object o = new int[] { 1, 2, 3 }; 
var array = (o as IEnumerable).Cast<object>().Select(x => x.ToString()).ToArray();