What is this `Object[*]` type I get with COM interop?

笑着哭i 提交于 2019-11-30 23:44:48

问题


I do C# excel interop. I call macros from C#, and I expect arrays of objects. I'm able to get 2-dimensional arrays of objects from the macros which returns 2-dimensional arrays.

However, an other (third party) macro is supposed to return a one-dimensional array. I can't get the (object[])xlApp.Run(...) working (it throws an exception), and the type info in the debugger says the result is of type Object[*]. The actual message from the exception is

Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'.

What is this Object[*] type and how do I retrieve a one-dimensional array from this ?

EDIT: It occurred to me that this could mean a SAFEARRAY of VARIANTS. But then, two questions arise: why is everything ok with 2-dimensional arrays ? How do I convert a SAFEARRAY to a C# array ?


回答1:


I foulnd various articles about your problem :

OPCFondation : Basically instead of declaring it as an array of objects, you can just declare it as an Array without providing any element type. So do not cast in Object[] but Array, and use a foreach loop to use the subarray.

foreach(object subobject in (Array)myarrayitem)
{
   //do stuff with the subobject, even browse further
}

This solution seems to work since you can find it again here.

On StackOverflow : they speak about arrays with lower bound > 0, which gives you the Object[*] type, with some links that can be interesting about the subject, but I think the first idea is the good one.




回答2:


Use

System.Array a = (System.Array)((object)  returnedObject );



回答3:


This was such a PITA. I had this code in two projects:

Workbook wb = null;
try
{
    wb = excel.Workbooks.Open(filePath, false, true, 5, null, "WrongPAssword");
}
catch
{
    return false;
}    

try
{

    Array links = (Array)wb.LinkSources(XlLink.xlExcelLinks);
    if (links != null)
    {

One worked the other did not. The Difference. Working one was targeting .Net 2.0 and other one was .Net 4.0 that was giving the error:

Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'.

Turns out if you change the Visual Studio version of this article from VS2005 to VS2010 the LinkSources datatype changes.

MSDN Workbook.LinkSources Method

VS2010:

Object LinkSources(
    Object Type
)

VS2005:

public virtual Object LinkSources (
    [OptionalAttribute] Object Type
)


来源:https://stackoverflow.com/questions/4539231/what-is-this-object-type-i-get-with-com-interop

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