Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#中的MS Word自动化-无法强制转换类型为';System.String[*]和#x27;输入';System.String[]和#x27;_C#_.net_Ms Word_Office Interop - Fatal编程技术网

C#中的MS Word自动化-无法强制转换类型为';System.String[*]和#x27;输入';System.String[]和#x27;

C#中的MS Word自动化-无法强制转换类型为';System.String[*]和#x27;输入';System.String[]和#x27;,c#,.net,ms-word,office-interop,C#,.net,Ms Word,Office Interop,我使用此代码获取MS Word 2007文档(.docx)中使用的标题字符串数组: 使用调试器,我看到arr动态分配了一个字符串数组,其中包含文档中所有标题的标题(大约40个条目)。到目前为止还不错 然后,我想访问字符串,但无论我如何访问,都会出现以下异常: InvalidCastException: Unable to cast object of type 'System.String[*]' to type 'System.String[]'. 我尝试了不同的访问

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

使用调试器,我看到
arr
动态分配了一个字符串数组,其中包含文档中所有标题的标题(大约40个条目)。到目前为止还不错

然后,我想访问字符串,但无论我如何访问,都会出现以下异常:

InvalidCastException: 
           Unable to cast object of type 'System.String[*]' to type 'System.String[]'.
我尝试了不同的访问字符串的方法:

按索引:

String arr_elem = arr[1];
通过强制转换为IEnumerable:

IEnumerable list = (IEnumerable)arr;
通过使用简单的foreach循环:

foreach (String str in arr)
{
   Console.WriteLine(str);
}
然而,无论我做了什么尝试,我总是以如上所示的相同异常结束


谁能解释一下我在这里遗漏了什么/我做错了什么?尤其是
String[*]
-它是什么意思?

String[]
是一个向量-一个一维、基于0的数组<但是,code>string[*]是一个恰好只有一个维度的常规数组。基本上,您必须将其作为
Array
处理,或者将数据复制出来,或者使用
Array
API而不是
string[]
API

这与
typeof(string).MakeArrayType()
(向量)和
typeof(string).MakeArrayType(1)
(一维非向量)之间的区别相同。

试试看

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

string myHeading = (string) arr.GetValue(1);

问题在于,您使用的是
动态
,而这种情况显然不是有意的。当动态运行时看到一个一维数组时,它会假定一个向量,并尝试索引到该向量中或将其作为向量枚举。这是一种罕见的情况,其中1D数组不是向量,因此必须将其作为
数组处理

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

你认为动态运行时试图像访问向量一样访问数组是一个bug吗?非常感谢你的解释:)@Gabe-是:谢谢你的解释:)你的第一行给我带来了一个InvalidCastException:无法将“System.String[*]”类型的对象强制转换为“System.String[]”类型。@sw u lasse:Oops,你说得对。我修好了。我的版本在C#3.0中工作,但在4.0中由于非标准数组的动态访问中存在明显的错误而中断。我已将此作为错误向MS提出:
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);
}