我的代码中有一行:
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();
关于c# - 在运行时将对象转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713998/