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

坚强是说给别人听的谎言 提交于 2019-11-27 06:14:02

问题


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.



来源:https://stackoverflow.com/questions/3731287/how-to-cast-system-object-to-system-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!