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

标签 c# casting

我的代码中有一行:

var objects = ExternalApiGetObjects(....);

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

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

如何转换我的 objectsstring[]

最佳答案

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/

相关文章:

c# - 查找文本 block /文本的高度

c# - 当 Dll 位于单独的文件夹中时免注册 COM

c# - 发送电子邮件的正确代码,asp.net

c# - 当所有 Controller 都继承自 AsyncController 时,这是一个好习惯吗?

c - 使用指向数值数据的 void* 指针的算术运算

c# - 查找 C# 中的文本差异并使用它们将文本恢复到之前的状态

编译器类型转换警告和错误

c++ - 在两个略有不同的 std::map 之间转换

go - 不能使用 (type interface{}) 作为类型 []Type

c++ - 当我们进行向下转型时内部会发生什么?