gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:07:52 25 4
gpt4 key购买 nike

我对在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com