创建扩展方法

扩展方法对于扩展我们不拥有的库的行为很有用。

由于编译器的语法糖,它们与实例方法类似:

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 中声明。