Collections 在VB6中创建自定义类的匿名实例

Collections 在VB6中创建自定义类的匿名实例,collections,vb6,Collections,Vb6,我知道在VB6中,用户定义的类不能指定构造函数。因此,给定在主代码块中标注的名为entities的集合对象和名为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

我知道在VB6中,用户定义的类不能指定构造函数。因此,给定在主代码块中标注的名为entities的集合对象和名为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
我不知道会有多少实体实例

蒂亚

仍在学习史蒂夫

试试看

然后

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

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

在课堂上:

Public Sub Init(ByVal NewName As string, ByVal CurName As String)
  mvarnewwNameValue = NewName
  mvarcurrNameValue = CurName
End Sub
在循环中: Set NewEntry=新条目 NewEntry.Init“weeble”、“bob” 实体。添加新条目


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

其他两个答案都很好,我已经使用了这两种方法。但我想我提出了另一个简单的解决方案。以下是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。换句话说,不要担心,继续前进。常常是好的建议@迪安娜:谢谢你的编辑。!:)显然不要听从我自己的建议。
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