「ルマンドとバームロールどっちが好き?」と訊かれると「バームロールです。」と即答します、とりこびとです。こんにちは♪
Visual Basic 2008では 拡張メソッド という機能が新しく追加されましたそうですねぇ。
Visual Basic Language Specification Version 9.0 : 9.2.7 Extension Methods
MSDN : 拡張メソッド (Visual Basic)
拡張メソッドを使用すれば、新しい派生型を作成しなくても、既に定義されているデータ型にカスタム機能を追加することが可能になります。
ですって。どんな感じに書くのかってぇと、ここ↓に書いてありました。すごく手取り足取りです♪
MSDN : 拡張メソッドを作成する
拡張メソッドはモジュールの中で宣言できると。んでもって、System.Runtime.CompilerServices 名前空間のExtensionAttribute クラスでマークする必要がある、と。あとは、最初のパラメータの型は、拡張するデータ型に設定しなきゃいけないのですね。
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Namespace SilverBouquet.Collections.Generic
Public Module ListExtensions
<Extension()> _
Public Sub Shuffle(Of T)(ByVal list As List(Of T))
Dim r As New Random()
For i As Integer = 0 To list.Count - 1
Dim value As Integer = r.Next(list.Count)
Dim temp As T = list.Item(i)
list.Item(i) = list.Item(value)
list.Item(value) = temp
Next
End Sub
End Module
End Namespace
ジェネリックとかもちゃんと書けますね。
んでもって使うときはこっち↓ですね。こちらもすごく手取り足取りです♪
MSDN : 方法 : 拡張メソッドを呼び出す
Imports System.Collections.Generic
Imports SilverBouquet.Collections.Generic.ListExtensions
Module Program
Public Sub Main()
Dim aList As New List(Of Integer)(New Integer() {1, 2, 3, 4, 5})
aList.Shuffle()
End Sub
End Module
ふむ、モジュールまでインポートして拡張メソッドまでスコープに含めてしまうことによって、インスタンスメソッドのように使用できるようになると。へ~。
さて、どうなってのかしらん♪
宿題~宿題~。