List(Of T).ForEach(Action(Of T))

中の技術日誌:技術解説 .NET 2.0 ジェネリック(Generics) 第2回 List<T>.ForEach(Action<T>)
List<T>の各項目に対して、Action<T>に指定したデリゲートメソッドを実行してくれるらしいです。・・・使ったことなかったなぁ。orz


[Visual Basic]


Imports System
Imports System.Collections.Generic


Public Class Program


Public Shared Sub Main()

Dim p As New Program

p.SampleMethod()

End Sub


Public Sub SampleMethod()

Dim words As New List(Of String)

words.Add("わんわん")
words.Add("にゃんにゃん")
words.Add("ひひーん")
words.Add("ぱおーん")

Dim outputAction As New Action(Of String)(AddressOf Me.Output)

words.ForEach(outputAction)

End Sub


Public Sub Output(ByVal word As String)

Console.WriteLine("「{0}」ってゆってみ?", word)

End Sub


End Class

んでもって、デリゲート渡してみるとどうなるのか?(以下参照)って〜と・・・コンパイルエラー。


Imports System
Imports System.Collections.Generic


Public Class Program


Public Shared Sub Main()

Dim p As New Program

p.SampleMethod()

End Sub


Public Sub SampleMethod()

Dim words As New List(Of String)

words.Add("わんわん")
words.Add("にゃんにゃん")
words.Add("ひひーん")
words.Add("ぱおーん")

Dim dlgt As New OutputDelegate(AddressOf Me.Output)

Dim outputAction As New Action(Of String)(dlgt)

words.ForEach(outputAction)

End Sub


Public Delegate Sub OutputDelegate(ByVal text As String)


Public Sub Output(ByVal word As String)

Console.WriteLine("「{0}」ってゆってみ?", word)

End Sub


End Class


Dim outputAction As New Action(Of String)(dlgt)
のところで、

'System.Action(Of String)' はデリゲート型です。唯一のコンストラクタへの引数として単一の 'addressof' 式が必要です。
っていわれました。単一の 'addressof' 式が必要らしいです。なんか特別っぽいなぁ。