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

前端 未结 6 1926
余生分开走
余生分开走 2021-02-19 17:57

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:32

    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.

提交回复
热议问题