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

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

    Alternative answer: generics.

    public static T[] CreateProperties(IProperty[] properties)
        where T : class, new()
    {
        //Empty so return null
        if (properties==null || properties.Length == 0)
            return null;
    
        //Check the type is allowed
        CheckPropertyTypes("CreateProperties(Type,IProperty[])",typeof(T));
    
        //Convert the array of intermediary IProperty objects into
        // the passed service type e.g. Service1.Property
        T[] result = new T[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            T[i] = new T();
            ServiceUtils.CopyProperties(properties[i], t[i]);
        }
        return result;
    }
    

    Then your calling code becomes:

    Property[] props = ObjectFactory.CreateProperties(properties);
    _service.SetProperties(folderItem.Path, props);
    

    Much cleaner :)

提交回复
热议问题