Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

c# - object to string array

I am trying to convert an object (is declared here as 'obj': object is array, primitive) to a string array.

object can be anything uint[], int16[], etc.

I have been trying to use

string[] str = Array.ConvertAll<object, string>((object[])obj, Convert.ToString);

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;

or

IEnumerable<object> list = obj as IEnumerable<object>
object[] arr = (object[])list;

I saw postings regarding value type and reference type issue on casting.

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.

thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

Casting to just IEnumerable will work though. Heck, you could cast to Array if you wanted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...