Unable to cast object of type 'System.Object[]' to 'MyObject[]', what gives?

前端 未结 6 1831
忘掉有多难
忘掉有多难 2021-02-19 18:09

Scenario:

I\'m currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I hav

6条回答
  •  日久生厌
    2021-02-19 18:35

    As others have said, the array has to be of the right type to start with. The other answers have shown how to convert a genuine object[] after the fact, but you can create the right kind of array to start with using Array.CreateInstance:

    object[] result = (object[]) Array.CreateInstance(type, properties.Length);
    

    Assuming type is a reference type, this should work - the array will be of the correct type, but you'll use it as an object[] just to populate it.

提交回复
热议问题