什么是字符串[*],我该如何转换? [英] What is a String[*] and how do I cast it?

查看:101
本文介绍了什么是字符串[*],我该如何转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在很不幸,不得不通过COM Interop从C#调用VBA宏。宏返回一个字符串数组,看起来像:

I'm currently in the unfortunate position of having to call a VBA macro from C#, via the COM Interop. The macro returns an array of strings and looks something like:

Public Function Foo() As String()

然后我试图将其转换为C#中的字符串数组,如下所示:

which I'm then trying to cast to an array of strings in C# like this:

var result = (string[])xlApp.Run("Foo", ... missing args ...)

然后会导致运行时错误:

which then results in the runtime error:

无法投射对象

有人知道字符串[*]是什么,并且您对如何将其转换为C#字符串[]有任何想法吗?此演员表可在我创建的一个简单测试用例中使用。我唯一看到的区别是,在简单情况下,我在VBA中的数组的类型为string(0到5),而在更复杂的情况下,我的数组的类型为string(1到6)。这可能是原因,如果是这样,我的VBA相当生锈-我该如何解决?

Does anyone know what a String[*] is, and do you have any idea of how to cast it to a C# string[]? This cast works in a simple test case I've created. The only difference I can see, is that in the simple case, my array in VBA is of type string(0 to 5) whereas in the more complex case, it's of type string(1 to 6). Could this be the reason and if so, my VBA is rather rusty - how do I fix it?

非常感谢,

Jon

Many thanks,
Jon

推荐答案

您的代码为

var result = (string[])xlApp.Run("Foo", ... missing args ...);

正如您所指出的,基于1的数组与基于0的数组存在不同的行为在VB中使用数组来执行您的代码。

As you have pointed out there is different behaviour with a 1-based array, with a zero-based array in VB your code does work.

您可以得到如下数据

var result = (Array)xlApp.Run("Foo", ... missing args ...);

var stringsResult = result.Cast<string>[];

这为您提供了IEnumerable字符串

This gives you an IEnumerable of string

这篇关于什么是字符串[*],我该如何转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆