简体   繁体   中英

Using ConvertAll to conver to array of objects

Am I misunderstanding what ConvertAll does or just not understanding something, because I took it to be change the type and not just cast.

So I'm wondering how a StringBuilder (or any class) can be converted to another base class (or in this case object) and still keep its data and type.

StringBuilder[] y = new StringBuilder[] { new StringBuilder("a"), new StringBuilder("b"), new StringBuilder("c") };
object[] objectArray1 = Array.ConvertAll<StringBuilder, object>(y, (x2) => (object)x2);

In the above, the new array is of objects, but still contains StringBuilder items. I thought the new array would be of the new type, so essentially lose all the original data, eg converting from int to string via a conversion would give you a brand new array of strings.

As in,

string[] array2 = Array.ConvertAll(array1,
        element => element.ToString());

Would give you a new array of strings.

thanks.

What ConvertAll() does is change the type of the reference. So you have a StringBuilder reference, and you copy that reference to a variable of type object :

var builder = new StringBuilder();
builder.AppendLine("Hello, World!");

object converted = (object)builder;

Now converted holds an object reference, but the actual object it's pointing to still is the StringBuilder that you instantiated.

The same is happening in the delegate you create. You can't just cast something to a base class and "cut off" all parts that aren't in the base class.

If you have a scenario where you think you need this, create a custom conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM