问题描述
我正在尝试将一个对象(在此处声明为obj":对象是数组,原语)转换为字符串数组.
I am trying to convert an object (is declared here as 'obj': object is array, primitive) to a string array.
object 可以是任何 uint[]、int16[] 等.
object can be anything uint[], int16[], etc.
我一直在尝试使用
string[] str = Array.ConvertAll<object, string>((object[])obj, Convert.ToString);
当我尝试将未知类型的对象转换为 object[] 时会出现问题.我遇到了铸造错误.
The problem occurs when I try to cast the unknown type object into object[].I have been getting casting error.
我做过的一次失败的尝试是使用
One attempt I made, which failed, was using
object[] arr = (object[])obj;
或
IEnumerable<object> list = obj as IEnumerable<object>
object[] arr = (object[])list;
我在转换时看到了关于值类型和引用类型问题的帖子.
I saw postings regarding value type and reference type issue on casting.
是否有一个简单的代码可以处理转换为 object[] 而不管对象的类型,只要它是一个数组?我试图避免手动处理所有可能的类型转换.
Would there be a simple code that can handle casting to object[] regardless of type of object, as long as it is an array ?I am trying to avoid manual handling of every possible type casting.
提前致谢
推荐答案
你可以使用每个数组都实现了 IEnumerable
的事实:
You can use the fact that every array implements IEnumerable
:
string[] arr = ((IEnumerable)obj).Cast<object>()
.Select(x => x.ToString())
.ToArray();
这将在将基元转换为字符串之前适当地装箱.
This will box primitives appropriately, before converting them to strings.
转换失败的原因是尽管 reference 类型的数组是协变的,value 类型的数组不是:
The reason the cast fails is that although arrays of reference types are covariant, arrays of value types are not:
object[] x = new string[10]; // Fine
object[] y = new int[10]; // Fails
强制转换为 IEnumerable
也可以.哎呀,如果你愿意,你可以转换为 Array
.
Casting to just IEnumerable
will work though. Heck, you could cast to Array
if you wanted.
这篇关于对象到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!