一个简单的 C# DLL - 我如何从 Excel、Access、VBA、VB6 调用它? [英] A Simple C# DLL - how do I call it from Excel, Access, VBA, VB6?

查看:32
本文介绍了一个简单的 C# DLL - 我如何从 Excel、Access、VBA、VB6 调用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 C# 编写的简单类库.

I have a simple class library written in c#.

using System;
namespace TestDll
{
    public class Test
    {
        public string HelloWorld
        {
            get
            {
                return "Hello World";
            }
        }
    }
}

我的问题是如何从 Microsoft Office Visual Basic(我认为是 VB6)调用这个 HelloWorld 函数?

My question is how can I call this HelloWorld function from Microsoft Office Visual Basic (which I think is VB6)?

我的第一步是添加 DLL 作为引用 - 但在浏览和选择编译的 DLL 时,消息无法添加对指定文件的引用".被扔了.

My first step was to add the DLL as a reference - but on browsing and selecting the compiled DLL the message "Can't add a reference to the specified file." was thrown.

谁能为我指出正确的方向,让我知道为什么/如何让这个工作?

Can anyone point me in the right direction as to why/how to get this working?

提前致谢!

推荐答案

您无法通过 COM 互操作访问静态成员.事实上,您的代码甚至无法编译,该方法应该在一个类中.您可以这样做:

You can't access a static member via COM interop. In fact your code doesn't even compile, the method should be in a class. Here is how you can do it:

[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("01A31113-9353-44cc-A1F4-C6F1210E4B30")]  //Allocate your own GUID
public interface _Test
{
    string HelloWorld { get; }
}

[ClassInterface(ClassInterfaceType.None)]
[Guid("E2F07CD4-CE73-4102-B35D-119362624C47")]  //Allocate your own GUID
[ProgId("TestDll.Test")]
public class Test : _Test
{
    public string HelloWorld { get { return "Hello, World! "; } }
}

在项目属性 Build 选项卡中,选择 Register for COM interop.所以你可以很快看到结果.要在另一台机器上安装 dll,您需要使用 regasm.

The project properties Build tab, select Register for COM interop. So you can see the results quickly. To install the dll on another machine you need to use regasm.

然后消费这个:

Dim o : Set o = CreateObject("TestDll.Test")
MsgBox o.HelloWorld

您也可以引用 dll 并使用早期绑定:

You can also reference the dll and use early binding:

Dim o As TestDll.Test
Set o = New TestDll.Text
MsgBox o.HelloWorld

这篇关于一个简单的 C# DLL - 我如何从 Excel、Access、VBA、VB6 调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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