问题描述
如果我在 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# 类的静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!