VBScript只喜欢处理包含VARIANTS的SAFEARRAY.而且它喜欢把这些在COM方法或属性中的变量放在VARIANTS中.因此,您需要构建一个包含VARIANT类型的SAFEARRAY的VARIANT属性.以下C#代码执行此操作.首先使用一个简单的对象数组,然后再显示我们可以将任何其他托管类型的数组转换成一个对象数组,以使编组代码将它转换成为我们的VARIANT的SAFEARRAY.
using System; using System.Runtime.InteropServices; using System.Linq; namespace StackOverflow { [ComVisible(true)] [Guid("2F4C19A6-9BB9-4ACF-90D1-BAF48696740A")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] public interface IMyArrayDemo { [DispId(1)] int Count { [return: MarshalAs(UnmanagedType.I4)] get; } [DispId(2)] object Data { [return: MarshalAs(UnmanagedType.Struct,SafeArraySubType = VarEnum.VT_ARRAY)] get; } [DispId(3)] object Names { [return: MarshalAs(UnmanagedType.Struct,SafeArraySubType = VarEnum.VT_ARRAY)] get; } } [ComVisible(true)] [Guid("7EF75834-22BE-4861-879B-EA0CE20E46E9")] [ClassInterface(ClassInterfaceType.None)] [ProgId("StackOverflow.MyArrayDemo")] public class MyArrayDemo : IMyArrayDemo { object[] mData = new object[10] { 0,1,2,3,5,8,13,21,34 }; string[] mNames = new string[5] {"one","two","three","four","five"}; public int Count { get { return mData.Length; } } public object Data { get { return mData; } } public object Names { get { return mNames.Cast<object>().ToArray(); } } } }
这可以使用以下vbscript进行测试:
Option Explicit Sub Main Dim o,v Set o = CreateObject("StackOverflow.MyArrayDemo") WScript.Echo "Count " & o.Count & " type: " & TypeName(o.Data) & " names: " & TypeName(o.Names) For Each v in o.Data : WScript.Echo CStr(v) : Next For Each v in o.Names : WScript.Echo v : Next End Sub Main
您可以看到这里报告的类型为Variant() – 即:一个变体数组.
C:\Users\pat>\windows\SysWOW64\cscript.exe -nologo arraytest.vbs Count 10 type: Variant() names: Variant() 0 1 1 2 3 5 8 13 21 34 one two three four five