简体   繁体   中英

Dimension of System.Object[*] C#

I am converting an Excel VSTO addin from VB.NET to C#. I am struck with getting the dimension of the System.object[*] returned by the Application.Evaluate() function.

I get the error message below during the runtime when the function is called.

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

Below are the original VB.NET code followed by the C# code. I had no issues with VB.NET code.

I tried to cast to Array, dynamic but of no use. Is there any alternative way to achieve my goal of getting the dimension of the Excel Application.Evaluate() function?

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

Below is original VB.NET Sub function.

    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

Below is the converted code in C#

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

The converted function is below.

    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;
    }

I am able to resolve this issue through some hints provided above. Below is the code which is working.

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM