将类成员从子类传递到另一个成员

问题描述 投票:0回答:1

这是一个简单的问题,有一个简单的解决方法,但是如果有解决方案,它将使我的代码更简单。

我的有效代码是这种类型:

Sub test()

If Condition Then

    Set classmember = New Class1
    *Instructions to execute with classmember*

    Else: classmember = New class2
    *Instructions to execute with classmember*

End If

End Sub

我想在一个单独的子代码中执行这些指令。如果我这样做了,那么当我切换到另一个子项时,即使是静态的,我的类成员也被设置回variant。我试图执行一个函数(类成员)以传递该类成员,该对象不支持该方法。

当我将其声明为public时,它可以工作,但这是创建字典条目的临时变量。向字典添加条目并删除项目也可以,但是在一般情况下,我正在寻找解决方案。

如果没有,我想所有临时变量的公共字典/集合都是可以接受的解决方案?

下面的真实代码:

Sub peupler_dictionnaire_configs()

For iLigneAnnuaireWs = 3 To 22          '

    Select Case WsCfg.Cells(iLigneAnnuaireWs, 11)

        Case "nautique"                 

        Set CfgTemp as New Cfg_Naut  'temp class member to populate the DictCfg dictionary

     End Select

Cfgtemp.AdresseCfg(1, 1) = WsCfg.Cells(iLigneAnnuaireWs, 4).Value
Cfgtemp.AdresseCfg(1, 2) = WsCfg.Cells(iLigneAnnuaireWs, 5).Value
Cfgtemp.AdresseCfg(2, 1) = WsCfg.Cells(iLigneAnnuaireWs, 6).Value
Cfgtemp.AdresseCfg(2, 2) = WsCfg.Cells(iLigneAnnuaireWs, 7).Value

Cfgtemp.Read_Cfg

'add entry to dictionary
 DictCfg.Add WsCfg.Cells(iLigneAnnuaireWs, 1), Cfgtemp

'reset of the temp class member
 Set CfgNautTemp = Nothing



Next iLigneAnnuaireWs

End Sub
excel vba class
1个回答
0
投票

看起来像继承的案例。

您需要一个父级接口类,该类具有Class1Class2中的所有常用功能;我们称之为ParentClass

作为示例,假设您有一个通用函数,该函数不带参数,并返回一个字符串。

Class ParentClass将具有此代码:

Function testFunction() As String
End Function

然后[Class Class1将实现ParentClass及其所有功能(除了Class1特有的任何功能。要实现一个功能,请在其前加上父类的名称。

因此,类Class1的代码可能看起来像这样:

Implements ParentClass

Function ParentClass_testFunction() As String
    ParentClass_testFunction = "Hello world! I'm the first child!"
End Function

Class2的代码可能看起来像这样:

Implements ParentClass

Function ParentClass_testFunction() As String
    ParentClass_testFunction = "Hello world! I'm the second child!"
End Function

在您的主代码中,您将dim变量作为ParentClass,并且在实际创建实例时,将使用子类。

例如,此代码首先打印“ Hello world!我是第一个孩子!”,然后显示“ Hello world!我是第二个孩子!”。

Dim x As ParentClass

Set x = New Class1
MsgBox x.testFunction

Set x = New Class2
MsgBox x.testFunction

使用Dim语句创建变量是这里的关键;如果您不使用dim,它会自动创建为variant,这就是您将其传递给的任何功能。

© www.soinside.com 2019 - 2024. All rights reserved.