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

前端 未结 6 1924
余生分开走
余生分开走 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:33

    Basically, no. There are a few, limited, uses of array covariance, but it is better to simply know which type of array you want. There is a generic Array.ConvertAll that is easy enough (at least, it is easier with C# 3.0):

    Property[] props = Array.ConvertAll(source, prop => (Property)prop);
    

    The C# 2.0 version (identical in meaning) is much less eyeball-friendly:

     Property[] props = Array.ConvertAll(
         source, delegate(object prop) { return (Property)prop; });
    

    Or just create a new Property[] of the right size and copy manually (or via Array.Copy).

    As an example of the things you can do with array covariance:

    Property[] props = new Property[2];
    props[0] = new Property();
    props[1] = new Property();
    
    object[] asObj = (object[])props;
    

    Here, "asObj" is still a Property[] - it it simply accessible as object[]. In C# 2.0 and above, generics usually make a better option than array covariance.

提交回复
热议问题