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

前端 未结 6 1851
忘掉有多难
忘掉有多难 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:37

    in C# 2.0 you can do this using reflection, without using generics and without knowing the desired type at compile time.

    //get the data from the object factory
    object[] newDataArray = AppObjectFactory.BuildInstances(Type.GetType("OutputData"));
    if (newDataArray != null)
    {
        SomeComplexObject result = new SomeComplexObject();
        //find the source
        Type resultTypeRef = result.GetType();
        //get a reference to the property
        PropertyInfo pi = resultTypeRef.GetProperty("TargetPropertyName");
        if (pi != null)
        {
            //create an array of the correct type with the correct number of items
            pi.SetValue(result, Array.CreateInstance(Type.GetType("OutputData"), newDataArray.Length), null);
            //copy the data and leverage Array.Copy's built in type casting
            Array.Copy(newDataArray, pi.GetValue(result, null) as Array, newDataArray.Length);
        }
    }
    

    You would want to replace all the Type.GetType("OutputData") calls and the GetProperty("PropertyName") with some code that reads from a config file.

    I would also use a generic to dictate the creation of SomeComplexObject

    T result = new T();
    Type resultTypeRef = result.GetType();
    

    But I said you didn't need to use generics.

    No guarantees on performance/efficiency, but it does work.

提交回复
热议问题