.net - 如何在 VBA 中使用 .NET 类?语法帮助!

标签 .net vba com instantiation

好的,我有几个要在 VBA 中使用的 .NET 类。所以我必须通过 COM 注册它们。我想我(终于)弄清楚了 COM 注册,但现在我需要有关如何创建对象的语法方面的帮助。这是一些伪代码,显示了我正在尝试做的事情。

编辑:更改附加对象以返回 ArrayList 而不是 List

.NET 类看起来像这样......

public class ResourceManagment
{
    public ResourceManagment()
    {
        // Default Constructor
    }

    public static List<RandomObject> AttachedObjects()
    {
        ArrayList list = new ArrayList();
        return list;
    }
}

public class RandomObject
{
    // 
    public RandomObject(int someParam)
    {

    }

}

好的,这就是我想在 VBA 中做的事情(在 C# 中演示),但我不知道如何......
public class VBAClass
{
    public void main()
    {
        ArrayList myList = ResourceManagment.AttachedObjects();
        foreach(RandomObject x in myList)
        {
            // Do something with RandomObject x like list them in a Combobox
        }
    }
}

需要注意的一件事是 RandomObject 没有公共(public)默认构造函数。所以我不能像 Dim x As New RandomObject 那样创建它的实例. MSDN 说你不能通过 COM 实例化一个没有默认构造函数的对象,但是如果它是由另一种方法返回的,你仍然可以使用该对象类型... Types must have a public default constructor to be instantiated through COM. Managed, public types are visible to COM. However, without a public default constructor (a constructor without arguments), COM clients cannot create an instance of the type. COM clients can still use the type if the type is instantiated in another way and the instance is returned to the COM client. You may include overloaded constructors that accept varying arguments for these types. However, constructors that accept arguments may only be called from managed (.NET) code.
补充:这是我在 VB 中的尝试:
Dim count As Integer
count = 0
Dim myObj As New ResourceManagment
For Each RandomObject In myObj.AttachedObjects
    count = count + 1
Next RandomObject

最佳答案

您的问题是 AttachedObjects()方法是静态的。 COM 不能做静态方法。在 COM 中,您可以做的唯一“静态”操作是“实例化一个类”。

因此,为了调用AttachedObjects VBA 中的方法,只需将其设为非静态(即删除其定义中的 static 关键字)。除此之外,该方法可能与现在完全一样。而且您的 VBA 代码似乎也可以 - 一旦您修改了方法,应该可以工作。

以防万一它不起作用,这是下一个问题:你到底得到了什么错误,在什么时候?

关于.net - 如何在 VBA 中使用 .NET 类?语法帮助!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2560287/

相关文章:

algorithm - 将迭代算法转换为递归算法的问题

c++ - 如何在 Visual Studio 2012 中创建 HelloWorld COM Interop

c# - 如何将字符串参数从 C++ com 传递给 C#?

.net - 在对象列表中搜索所有属性

c# - 返回实现通用接口(interface)的类的类型

c# - 类中所有值类型的通用函数

html - excel截断从html中提取的非常大的整数

c# - 在 C# 应用程序中嵌入 LuaInterface 性能很慢?

excel - 基于另一张工作表中的公式的条件格式

audio - 媒体基金会 IMFMediaSource::CreatePresentationDescriptor 调用永无止境