c# 我可以防止我的构造函数参数与 VBA 实例化冲突吗?

标签 c# vba

我对在 VBA 环境中使用类时如何覆盖需要参数的构造函数感到有点困惑。

什么有效?

我在一个库中创建了几个类,每个类都有一个接口(interface),以便在 VBA 中使用该库时实现完全的智能感知兼容性

有或没有构造函数,这些类对我来说都很好,例如

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("JamHeadArt.ClassEX")]
[Guid("XYZ")]
public partial class ClassEX : IClassEX
{

    public ClassEX()
    {
        // Empty constructor here, some of mine have processes, all work well
    }  

    // Methods/ Properties as outlined by the interface below
}

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("ABC")]
public interface IClassEx
{
    // Various methods / fields / properties to be implemented by ClassEX
}

然后我添加对我的库的引用并在 VBA 中编写简单的代码行来实例化和访问我的类:

Sub Test()
Dim t As JamHeadArt.ClassEX
Set t = New JamHeadArt.ClassEX
' Using t.dot then provides all the methods needed '
End Sub

出了什么问题?

当我在类中创建带有参数(即使是可选的)的构造函数时,VBA 将停止允许我创建这些类的实例,它告诉我“New”关键字无效并且实际上不允许我选择如果我直接使用 Dim t As New JamHeadArt.ClassEx,即使参数设置为可选(因此实际上不需要)

,也可以从我的库中的智能感知列表中获取类

这里令人讨厌的是 - 我实际上并不希望我的 VBA 实例通过构造函数接受参数,它们主要用于单元测试并且它们是可选字符串,因此默认为““...所以我想我的问题是类似

是否可以覆盖任何构造函数参数以便在 VBA 环境中引用时忽略它们?

例如我真的希望我的构造函数看起来像这样:

public ClassEX(string s = "")
{

} 

在 VBA 中,它应该像以前一样工作 Dim t As New JamHeadArt.ClassEX - 但它不会在那里使用那个可选字符串!

最佳答案

您可以添加一个额外的构造函数,例如:

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("JamHeadArt.ClassEX")]
[Guid("XYZ")]
public partial class ClassEX : IClassEX
{
    public ClassEX()
    {
        // Empty constructor here, some of mine have processes, all work well
    }  

    public ClassEX(string foo)
    {
        // additional constructor, can be used for unit testing etc.
    }  

    // Methods/ Properties as outlined by the interface below
}

关于c# 我可以防止我的构造函数参数与 VBA 实例化冲突吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53987605/

相关文章:

c# - 如何在Acumatica ERP系统中自定义屏幕AP Release All和AR Relase All

vba - 调用堆栈中未显示的背景宏/子程序

python - 从 PowerPoint/VBA 调用 python 脚本

Excel VlookUp从另一个工作簿将左侧单元格插入VBA

javascript - 是否有访问 JSON.parse XMLHTTPRequest.responseText 的通用方法?

c# - 图像在 chrome 和 Firefox 中看起来不同

c# - 如何使用 postgresql 函数获取多结果集

c# - 在鼠标悬停在文本上时显示工具提示

vba - 如何在 VBA 中格式化文本/字符串?

excel - 启动多个 Excel 实例后,如何获取所有实例的应用程序对象?