我必须在包含数组的vb6中使用C#类。 我将它们编组为安全阵列,但我无法在VB6中重新编写它们,尽管在观察中我可以看到它们具有正确的类型。 当我在结构中使用相同的编组时,它工作正常。它们之间的区别在于,在结构中我有字段,在类中我有属性,所以我认为我有一些问题,但我无法找到它。
这是我的测试类:
[ComVisible(true)]
[Guid("179181EF-8689-4CCA-B43E-34145F5A9608")]
public interface IBook
{
string Title { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; }
string[] Keywords { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] get; [param: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] set; }
int[] Years { [return: MarshalAs(UnmanagedType.SafeArray)] get; [param: MarshalAs(UnmanagedType.SafeArray)] set; }
}
[ComVisible(true)]
[Guid("61AF9F28-3588-4C26-A971-2C42CFC2040B")]
[ClassInterface(ClassInterfaceType.None)]
public class Book : IBook
{
public string[] Keywords { get; set; }
public string Title { get; set; }
public int[] Years { get; set; }
}
这是我的vb6代码:
Dim book As New TestProject.book
Set book = New TestProject.book
ReDim book.years(1 To 3)
当我尝试编译它时,我收到编译错误:"找不到方法或数据成员"
答案 0 :(得分:1)
我在c#中复制代码以找到问题。看起来在c#中你必须使用临时变量(temp)
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
Test.Book book1 = new Test.Book { Keywords = new string[] { "a", "b", "c" }, Title = "123", Years = new int[] { 30 } };
Test.IBook Ibook1 = (Test.IBook)book1;
Test.Book book2 = (Test.Book)Ibook1;
int[] temp = Ibook1.Years;
Array.Resize(ref temp, 3);
Ibook1.Years = temp;
}
}
public class Test
{
[ComVisible(true)]
[Guid("179181EF-8689-4CCA-B43E-34145F5A9608")]
public interface IBook
{
string Title { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; }
string[] Keywords { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] get; [param: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] set; }
int[] Years { [return: MarshalAs(UnmanagedType.SafeArray)] get; [param: MarshalAs(UnmanagedType.SafeArray)] set; }
}
[ComVisible(true)]
[Guid("61AF9F28-3588-4C26-A971-2C42CFC2040B")]
[ClassInterface(ClassInterfaceType.None)]
public class Book : IBook
{
public string[] Keywords { get; set; }
public string Title { get; set; }
public int[] Years { get; set; }
}
}
}