how to upcast object array to another type of object array in C#?

前端 未结 3 958
耶瑟儿~
耶瑟儿~ 2021-01-22 12:29

I want to upcast object array to different array of different object type like below

object[] objects; // assuming that it is non-empty

CLassA[] newObjects = obj

相关标签:
3条回答
  • 2021-01-22 12:57

    As this post suggests, you may be able to do the following trick (untested):

    newObjects = (ClassA[])(object)objects;
    

    Note that in C# 4.0 you won't need to cast, you will be able to directly assign newObjects = objects.

    0 讨论(0)
  • 2021-01-22 13:22
    using System.Linq;
    
    newObjects = objects.Select(eachObject => (ClassA)eachObject).ToArray();
    
    0 讨论(0)
  • 2021-01-22 13:22

    Or I guess you could try something like this for even shorter syntax:

    newObjects = objects.Cast<ClassA>().ToArray();
    
    0 讨论(0)
提交回复
热议问题