我可以通过 COM 从 VBA 调用 C# 类的静态方法吗?

8

本文介绍了我可以通过 COM 从 VBA 调用 C# 类的静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果我在 C#/.NET 类库中定义一个类,那么通过使其 COM 可见,我可以实例化该类并使用 COM 从 VBA 调用其方法.

If I define a class in a C#/.NET class library, then by making it COM visible I can instantiate the class and call its methods from VBA using COM.

有没有办法从 VBA 中调用此类的静态方法?

Is there any way to call the static methods of such a class from VBA?

推荐答案

COM不支持静态方法,COM对象的实例不调用静态方法.相反,在您的静态方法上设置 ComVisible(false),然后创建一个实例方法来包装它:

COM does not support static methods, and instances of COM objects do not invoke static methods. Instead, set ComVisible(false) on your static method, then make an instance method to wrap it:

[ComVisible(true)]
public class Foo
{
    [ComVisible(false)]
    public static void Bar() {}

    public void BarInst()
    {
        Bar();
    }
}

或者只是创建方法实例而不是静态的,然后一起忘记静态.

Or just make the method instance instead of static and forget static all together.

您没有必须将静态方法标记为对 COM 不可见,但它满足一些代码分析工具的要求,这些工具会警告您关于 COM 可见类型的静态方法,并清楚地表明静态方法不打算对 COM 可见.

You don't have to mark the static method as not visible to COM, however it satisfies some code analysis tools that would warn you about static methods on COM visible types, and makes it clear that the static method is not intended to be visible to COM.

这篇关于我可以通过 COM 从 VBA 调用 C# 类的静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14