|
分類:[VB.NET/VB2005 以降]
カスタムクラスに動的追加する方法
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim mydat As New BClass({ _
New AClass("a", "1"), _
New AClass("b", "2"), _
New AClass("c", "3")})
For Each dat In mydat2
Console.WriteLine(dat.a1 & " - " & dat.a2)
Next
End Sub
Public Class AClass
Public Sub New(ByVal a1 As String, ByVal a2 As String)
Me.a1 = a1
Me.a2 = a2
End Sub
Public a1 As String
Public a2 As String
End Class
Public Class BClass
Implements IEnumerable(Of AClass)
Private _BClass() As AClass
Public Sub New(ByVal pArray() As AClass)
_BClass = New AClass(pArray.Length - 1) {}
For i As Integer = 0 To pArray.Length - 1
_BClass(i) = pArray(i)
Next i
End Sub
Public Function GetEnumerator() As IEnumerator(Of AClass) _
Implements IEnumerable(Of AClass).GetEnumerator
Return DirectCast(_BClass, IEnumerable(Of AClass)).GetEnumerator
End Function
Private Function System_Collections_GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
Return Me.GetEnumerator
End Function
End Class
Button1_Click を実行
結果
a - 1
b - 2
c - 3
質問ですが、同じ結果を
初期化子を設定しないで行いたいです。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim mydat As New BClass({ _
New AClass("a", "1"), _
New AClass("b", "2"), _
New AClass("c", "3")})
上記の初期化子の部分を
Dim mydat As New BClass(New AClass() {})
設定しないで、追加する方法でおこないたいです。
End Sub
下記を実行しましたら、当然ですが最終の要素しか出力されません。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim a1ary() As String = {"a", "b", "c"}
Dim a2ary() As String = {"1", "2", "3"}
Dim mydat As New BClass(New AClass() {})
For j As Integer = 0 To a1ary.Length - 1
mydat = New BClass({New AClass(a1ary(j), a2ary(j))})
Next
For Each dat In mydat
Console.WriteLine(dat.a1 & " - " & dat.a2)
Next
End Sub
結果
c - 3
ご教授お願いします。
|