-->

How to cast System.Object[*] to System.Object[]

2019-01-19 01:56发布

问题:

When I Tried to return an Array in VFP9 language COM/DLL to my .NET C# project I receive a System.Object[*] array and I can not cast to System.Object[] (Without asterisk).

回答1:

Timwi's solution should work fine. You can do something a bit simpler using Linq:

object[] newArray = sourceArray.Cast<object>().ToArray();

In case you need to recreate a System.Object[*] to pass it back to VFP, you can use this overload of the Array.CreateInstance method:

public static Array CreateInstance(
    Type elementType,
    int[] lengths,
    int[] lowerBounds
)

You can use it as follows:

object[] normalArray = ...

// create array with lower bound of 1
Array arrayStartingAt1 =
    Array.CreateInstance(
        typeof(object),
        new[] { normalArray.Length },
        new[] { 1 });

Array.Copy(normalArray, 0, arrayStartingAt1, 1, normalArray.Length);


回答2:

Unfortunately, you cannot cast it directly. You can, however, create a new array of type object[] and copy the data over. Something like...

Array sourceArray = ...;

if (sourceArray.Rank != 1)
    throw new InvalidOperationException("Expected a single-rank array.");

object[] newArray = new object[sourceArray.Length];
Array.Copy(sourceArray, sourceArray.GetLowerBound(0),
           newArray, 0, sourceArray.Length);


回答3:

I had a similar issue. Got an array as a dynamic object from an interop assembly, also starting from index one. When I tried to convert this into an Array object, I got the same error message.
Doing as the other answers suggest did not work. For a strange reason, even reading the Length property raised the exception.
I found this answer, and it worked.
Apparently, if you use C# 4.0, you have to cast the dynamic to object first, then you can convert it to Array. In prior versions of .NET you can cast directly.
Here is an Explanation why.