MS Word Automation in C# - Unable to cast object of type 'System.String[*]' to type 'System.String[]'

后端 未结 3 1744
抹茶落季
抹茶落季 2021-01-04 19:37

I use this code to get a String array of headings used in a MS Word 2007 document (.docx):

dynamic arr = Document.GetCrossReferenceItems(WdReferenceType.wdRe         


        
3条回答
  •  暖寄归人
    2021-01-04 20:28

    The problem is that you're using dynamic in a situation where it apparently wasn't intended. When the dynamic runtime sees a 1D array, it assumes a vector, and tries to index into it or enumerate it as if it were a vector. This is one of those rare cases where you have a 1D array that is not a vector, so you have to handle it as an Array:

    Array arr = (Array)(object)Document.
                GetCrossReferenceItems(WdReferenceType.wdRefTypeHeading);
    // works
    String arr_elem = arr.GetValue(1);
    // now works
    IEnumerable list = (IEnumerable)arr; 
    // now works
    foreach (String str in arr)
    {
        Console.WriteLine(str);
    }
    

提交回复
热议问题