建立擴充套件方法

擴充套件方法對於擴充套件我們不擁有的庫的行為很有用。

由於編譯器的語法糖,它們與例項方法類似:

Sub Main()
    Dim stringBuilder = new StringBuilder()

    'Extension called directly on the object.
    stringBuilder.AppendIf(true, "Condition was true")

    'Extension called as a regular method. This defeats the purpose
    'of an extension method but should be noted that it is possible.
    AppendIf(stringBuilder, true, "Condition was true")

End Sub

<Extension>
Public Function AppendIf(stringBuilder As StringBuilder, condition As Boolean, text As String) As StringBuilder
    If(condition) Then stringBuilder.Append(text)

    Return stringBuilder
End Function

要獲得可用的擴充套件方法,該方法需要 Extension 屬性,需要在 Module 中宣告。