c# - 如何通过 COM 互操作将 VBA 变量数组数据类型传递到 C# 方法中

标签 c# .net vba com com-interop

目前,我正在尝试通过 COM 互操作将变体数据类型数组传递到 C# 方法中。问题是,将其传递为:

[MarshalAs(UnmanagedType.SafeArray)

但是这似乎不起作用,有人对我如何将其作为参数传递有任何提示吗?

这是我的完整 C# 源代码:

using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;

namespace ExpandExcel
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class ExpandExcelStandard
    {
        #region Public Static Methods

        [return: MarshalAs(UnmanagedType.SafeArray)]
        public static T[] RemoveDuplicates<T>([MarshalAs(UnmanagedType.SafeArray)] ref T[] arr)
        {
            // Creates a hash set based on arr
            HashSet<T> set = new HashSet<T>(arr);
            T[] resultArr = new T[set.Count];
            set.CopyTo(resultArr);
            return resultArr; // Return the resultArr
        }

        #endregion
    }
}

这是我的完整 VBA 源代码:

Sub main()
    Dim arr(1000000) As Variant

    Dim ExpandExcel As ExpandExcelStandard
    Set ExpandExcel = New ExpandExcelStandard

    For i = 0 To UBound(arr)
        Randomize
        arr(i) = Int((1000000 + 1) * Rnd)
    Next i

    Dim resultArr() As Variant

    resultArr = ExpandExcel.RemoveDuplicates(arr)
End Sub

最佳答案

不能在 COM 中使用泛型,不能使用静态函数等。 这是一个应该可以工作的类似代码:

VB

Sub main()
    Dim arr(1000000) As Variant

    For i = 0 To UBound(arr)
        Randomize
        arr(i) = Int((1000000 + 1) * Rnd)
    Next i

    Set ExpandExcel = CreateObject("ExpandExcelStandard") // I used late binding but early is fine too
    resultArr = ExpandExcel.RemoveDuplicates(arr)
End Sub

C#

[ProgId("ExpandExcelStandard")] // because I wanted late binding, I declared a progid
[ComVisible(true)]
public class ExpandExcelStandard
{
    // .NET object (w/o any Marshal spec) is passed as an automation Variant
    public object[] RemoveDuplicates(object[] arr) => new HashSet<object>(arr).ToArray();
}

关于c# - 如何通过 COM 互操作将 VBA 变量数组数据类型传递到 C# 方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60775491/

相关文章:

c# - 尝试删除带有子项的注册表项会导致错误

c# - !DumpStackObjects 显示重复实例?

excel - 当协调组合的数量未知时协调两个数据集/集合

c# - 什么是将参数传递给 SQL,为什么我需要它?

.net - 自动化测试.NET(Gallio?)

vba - 如何在 Excel/VBA 中获取 RGB 颜色对应的十六进制值?

excel - 在 Excel 中,我如何编写循环,除非满足条件,否则将继续删除单元格的内容?

c# - 字典方法 Remove 和 Clear (.NET Core) 在枚举期间修改集合。没有抛出异常

c# - 无法翻译 LINQ 表达式错误

c# - 如何对派生自基类的类隐藏作为基类中接口(interface)实现的一部分的方法?