.NET 4.0的Excel互操作问题的动态集合 [英] .NET 4.0 Excel Interop issues with dynamic collections

查看:156
本文介绍了.NET 4.0的Excel互操作问题的动态集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Excel中,你可以返回一个动态数组 System.Object的[*] ,使用了一系列对象 XValues​​ 。在.NET 3.5中,你可以通过它铸造和数组访问此对象中的元素,即:

In Excel you can return a dynamic array System.Object[*], from a series object using XValues. In .NET 3.5 you can access the elements in this object by casting it to and array, i.e.:

var values = (Array)series.XValues;

在.NET 4.0中,这不再有效,并且该消息

In .NET 4.0, this no longer works, and the message

无法投类型的对象System.Object的[*]'输入'System.Object的[]'

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

给出。

任何想法?下面不工作:

Any ideas? The following doesn't work:

  • 在铸造它的动态。
  • 它铸造于 System.Object的[*]
  • 只需配售对象的每一个循环。
  • 在尝试使用直接访问该值值[1] ,既不当转换为动态的。
  • Casting it as dynamic.
  • Casting it to a System.Object[*].
  • Just placing the object in a for each loop.
  • Trying to access the value directly using values[1], neither when cast as a dynamic.

在数组中的值都出现在但调试器。

The values inside the array do show up in the debugger however.

推荐答案

有两种不同类型的在.NET数组,一维向量和多维数组。你得到了后者的背,多维数组为1。等级如果非托管的code返回一个SAFEARRAY的下限是不是会发生这种情况0。

There are two distinct kind of arrays in .NET, a one dimensional 'vector' and multidimensional arrays. You got the latter back, a multidimensional array with a rank of 1. This will happen if the unmanaged code has returned a SAFEARRAY whose lower-bound isn't 0.

您可以阅读阵列与Array.GetValue的内容()。或将其转换,像这样的:

You can read the content of the array with Array.GetValue(). Or convert it, like this:

    private static object[] ConvertArray(Array arr) {
        int lb = arr.GetLowerBound(0);
        var ret = new object[arr.GetUpperBound(0) - lb + 1];
        for (int ix = 0; ix < ret.Length; ++ix) {
            ret[ix] = arr.GetValue(ix + lb);
        }
        return ret;
    }

测试:

    var native = Array.CreateInstance(typeof(object), new int[] { 42 }, new int[] { 1 });
    var dotnet = ConvertArray(native);


请注意:你可能有一个问题,在.NET 4.0中,最多的时候你一些COM类型库,办公室特别。该属性或方法可能会返回一个包含数组变量。结束了在你的C#程序的动态的。 C#编译器不产生适当的粘合剂code在这种情况下。各地通过铸造第一个(目标),然后(阵列)的工作。


NOTE: you may have a problem in .NET 4.0 and up when you some COM type libraries, Office in particular. The property or method may return a variant that contains an array. Ends up as dynamic in your C# program. The C# compiler does not generate the proper binder code in that case. Work around that by casting first to (object), then to (Array).

这篇关于.NET 4.0的Excel互操作问题的动态集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆