System.Object[*] C# 的维度

Dimension of System.Object[*] C#

我正在将 Excel VSTO 插件从 VB.NET 转换为 C#。我对获取 Application.Evaluate() 函数返回的 System.object[*] 的维度感到震惊。

我在调用函数时在运行时收到以下错误消息。

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

下面是原始 VB.NET 代码,后面是 C# 代码。我对 VB.NET 代码没有任何问题。

我尝试转换为数组,动态但没有用。有没有其他方法可以实现我获得 Excel Application.Evaluate() 函数维度的目标?

If GetDimension(xlapp.Application.Evaluate(FormulaString)) = 0 Then
    'The formula results in single value.
Else
     'The formula is Matrix Based. 
End If

下面是原始的VB.NET子函数。

    Private Function GetDimension(MatResult As Object) As Integer
        Dim i As Integer
        Dim LoopCheck As Boolean = True
        Dim RankException As Integer
        Dim Dimension As Integer
        i = 0
        Do
          i += 1
          Try
              RankException = UBound(MatResult, i)
          Catch ex As Exception
              Dimension = i - 1
              LoopCheck = False
          End Try

       Loop Until Not LoopCheck

       Return Dimension 
   End Function

下面是C#中转换后的代码

if(GetDimension(xlapp.Application.Evaluate(FormulaString)) == 0)
    //The formula results in single value.
else
     //The formula is Matrix Based. 

转换后的函数如下

    public int GetDimension(object MatResult)
    {
        int i;
        bool LoopCheck = true;
        int RankException;

        if (MatResult.GetType() == typeof(double) || MatResult.GetType() == typeof(string))
            return 0;

        int Dimension = 0;
        Array CastedMat = (Array)MatResult;
        i = 0;
        do
        {
            i++;
            try
            {
                RankException = CastedMat.GetLength(i);
            }
            catch (Exception ex)
            {
                Dimension = i - 1;
                LoopCheck = false;
            }
        }
        while (LoopCheck);

        return Dimension;
    }

我可以通过上面提供的一些提示解决这个问题。 以下是有效的代码。

    public int GetDimension(object MatResult)
    {
         int MatrixRank;

        if (MatResult.GetType() == typeof(double) || MatResult.GetType() == typeof(string))
            return 0;

        Array CastedMat = MatResult as Array;
        MatrixRank = CastedMat.Rank;
        return MatrixRank;
    }