【问题标题】:creating anonymous instances of a custom class in VB6在 VB6 中创建自定义类的匿名实例
【发布时间】:2012-02-28 06:06:01
【问题描述】:

我了解到,在 VB6 中,用户定义的类不能指定构造函数。因此,给定一个名为实体的 Collection 对象,在主代码块中标注尺寸和一个名为 Entity 的用户定义类:

Public Class Entry
'local variable(s) to hold property value(s)
Private mvarcurrNameValue As String 'local copy
Private mvarnewwNameValue As String 'local copy

Public Property Let newwNameValue(ByVal vData As String)
    mvarnewwNameValue = vData
End Property

Public Property Get newwNameValue() As String
    newwNameValue = mvarnewwNameValue
End Property

Public Property Let currNameValue(ByVal vData As String)
    mvarcurrNameValue = vData
End Property

Public Property Get currNameValue() As String
    currNameValue = mvarcurrNameValue
End Property
End Class

如何在 VB6 领域实现以下 C++/VB.NET 习语?

For Each foo In bar
   entities.Add (new Entity("Sinatra","Frank"))     'VB.NET seems to like this but not VB6
Next

我事先不知道会有多少个Entity实例。

TIA,

还在学习的史蒂夫

【问题讨论】:

    标签: collections vb6


    【解决方案1】:

    试试factory method

    Public function NewEntry(a, b) As Entry
       Dim o As Entry
       Set o = New Entry
       o.a = a
       o.b = b
       Set NewEntry = o
    End Function
    

    然后

    For Each foo In bar 
       entities.Add NewEntry("Sinatra","Frank")
    Next 
    

    【讨论】:

    【解决方案2】:

    要在对象实例上设置属性和调用方法,您需要先将其分配给变量。 分配后,您可以直接设置属性,也可以使用自定义的Init() 方法。

    在课堂上:

    Public Sub Init(ByVal NewName As string, ByVal CurName As String)
      mvarnewwNameValue = NewName
      mvarcurrNameValue = CurName
    End Sub
    

    在循环中: 设置 NewEntry = 新条目 NewEntry.Init "weeble", "bob" entity.Add NewEntry

    这些可以直接在您的循环中完成,也可以通过 MarkJ 所说的工厂函数完成。请注意,一旦将其传递给 .Add,您就可以重复使用该变量,只要将其设置为 New 实例即可。

    【讨论】:

      【解决方案3】:

      其他两个答案都很好,我已经使用了这两种方法。但我想我提出了另一个简单的解决方案。这是vanila VB6的做法:

      Dim tempEntity As Entity
      For Each foo In bar
         Set tempEntity = New Entity
         tempEntity.currNameValue = "Sinatra"
         tempEntity.newwNameValue = "Frank"
         Call entities.Add(tempEntity) 
         'Or if you prefer the no parens style use this:
         'entities.Add tempEntity
      Next foo
      

      关于命名约定的说明,前导小写方法/属性名称在 Java 中很常见,但在 .NET 或 VB6 中不常见。

      【讨论】:

      • +1。换句话说,不要担心它并继续前进。通常是很好的建议!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2011-01-10
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多