C#中的MS Word Automation - 无法将类型为'System.String [*]'的对象强制转换为'System.String []'

Las*_*sen 9 .net c# ms-word office-interop

我使用此代码获取MS Word 2007文档(.docx)中使用的标题字符串数组:

dynamic arr = Document.GetCrossReferenceItems(WdReferenceType.wdRefTypeHeading);
Run Code Online (Sandbox Code Playgroud)

使用调试器,我看到arr动态分配了一个String数组,其中包含文档中所有标题的标题(大约40个条目).到现在为止还挺好.

然后,我想访问字符串,但不管我怎么做,我得到以下异常:

InvalidCastException: 
           Unable to cast object of type 'System.String[*]' to type 'System.String[]'.
Run Code Online (Sandbox Code Playgroud)

我尝试过不同的访问字符串的方法:

按索引:

String arr_elem = arr[1];
Run Code Online (Sandbox Code Playgroud)

通过强制转换为IEnumerable:

IEnumerable list = (IEnumerable)arr;
Run Code Online (Sandbox Code Playgroud)

通过使用简单的foreach循环:

foreach (String str in arr)
{
   Console.WriteLine(str);
}
Run Code Online (Sandbox Code Playgroud)

但是,无论我尝试什么,我总是会遇到如上所示的相同异常.

任何人都可以解释我在这里失踪/我做错了什么?特别是String[*]- 它是什么意思?

Mar*_*ell 7

string[]是一个向量 - 基于1-d,0的数组.string[*]但是,它是一个恰好具有一个维度的常规数组.基本上,您将不得不处理它Array,并将数据复制出来,或使用ArrayAPI而不是string[]API.

这与typeof(string).MakeArrayType()(矢量)和typeof(string).MakeArrayType(1)(1-d非矢量)之间的差异相同.


Yah*_*hia 6

尝试

object arr_r = Document.GetCrossReferenceItems(WdReferenceType.wdRefTypeHeading);
Array arr = ((Array) (arr_r));

string myHeading = (string) arr.GetValue(1);
Run Code Online (Sandbox Code Playgroud)


Gab*_*abe 5

问题是您在dynamic显然不是故意的情况下使用。当动态运行时看到一维数组时,它假定一个向量,并尝试对其进行索引或枚举,就好像它是一个向量一样。这是您拥有不是向量的一维数组的罕见情况之一,因此您必须将其作为 处理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);
}
Run Code Online (Sandbox Code Playgroud)