Szukaj…


Uwagi

Metody rozszerzeń to metody ( Sub lub Function ), które dodają funkcjonalność do typu (który może być typem odniesienia lub typem wartości). Te typy mogą, ale nie muszą być Twoją własnością.

Mogą, ale nie muszą być w tym samym zestawie, co typ, który mają zmodyfikować. Możesz zezwolić na włączenie metod rozszerzania, izolując je we własnej przestrzeni nazw. Lub jeśli wolisz, możesz je zawsze udostępnić, włączając je w tym samym obszarze nazw, co zmodyfikowany typ (zakładając, że wszystkie odwołania do zestawu są na miejscu i są poprawne). Zobacz projekt Entity Framework Core 1.0 na GitHub, aby zobaczyć dobry przykład metod opt-in dla metod rozszerzenia.

Metody rozszerzenia w VB mają kilka wymagań:

  • Metody rozszerzenia mogą być deklarowane tylko w modułach.
  • Metody rozszerzeń muszą być ozdobione atrybutem Extension() .
  • Przestrzeń nazw ExtensionAttribute musi być dostępna w twoim module.
    Imports System.Runtime.CompilerServices
  • Pierwszy parametr metody musi być typu, do którego ta metoda zostanie dołączona.
  • Pierwszy parametr metody będzie reprezentował instancję, na której działa ta metoda. (Odpowiednik dla Me jeśli Me to metoda rzeczywistej instancji).
  • Metodę rozszerzenia można wywołać jako zwykłą metodę, podając wszystkie parametry, jeśli nie zostaną wywołane w utworzonym obiekcie.

Tworzenie metody rozszerzenia

Metody rozszerzeń są przydatne w celu rozszerzenia zachowania bibliotek, których nie posiadamy.

Są one używane podobnie jak metody instancji dzięki cukierowi syntaktycznemu kompilatora:

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

Aby mieć użyteczną metodę rozszerzenia, metoda wymaga atrybutu Extension i musi zostać zadeklarowana w Module .

Zwiększanie funkcjonalności języka dzięki metodom rozszerzeń

Dobrym zastosowaniem metody rozszerzenia jest uczynienie języka bardziej funkcjonalnym

Sub Main()
    Dim strings = { "One", "Two", "Three" }

    strings.Join(Environment.NewLine).Print()
End Sub

<Extension>
Public Function Join(strings As IEnumerable(Of String), separator As String) As String
    Return String.Join(separator, strings)
End Function

<Extension>
Public Sub Print(text As String)
    Console.WriteLine(text)
End Sub

Padding Numberics

Public Module Usage
  Public Sub LikeThis()
    Dim iCount As Integer
    Dim sCount As String

    iCount = 245
    sCount = iCount.PadLeft(4, "0")

    Console.WriteLine(sCount)
    Console.ReadKey()
  End Sub
End Module



Public Module Padding
  <Extension>
  Public Function PadLeft(Value As Integer, Length As Integer) As String
    Return Value.PadLeft(Length, Space(Length))
  End Function



  <Extension>
  Public Function PadRight(Value As Integer, Length As Integer) As String
    Return Value.PadRight(Length, Space(Length))
  End Function



  <Extension>
  Public Function PadLeft(Value As Integer, Length As Integer, Character As Char) As String
    Return CStr(Value).PadLeft(Length, Character)
  End Function



  <Extension>
  Public Function PadRight(Value As Integer, Length As Integer, Character As Char) As String
    Return CStr(Value).PadRight(Length, Character)
  End Function
End Module

Pobieranie wersji zestawu od silnej nazwy

Przykład wywołania metody rozszerzenia jako rozszerzenia i jako zwykłej metody.

public Class MyClass  
  Sub Main()
        
        'Extension called directly on the object.
        Dim Version = Assembly.GetExecutingAssembly.GetVersionFromAssembly()

        'Called as a regular method.
        Dim Ver = GetVersionFromAssembly(SomeOtherAssembly)

    End Sub
End Class

Metoda rozszerzenia w module. Ustaw moduł jako publiczny, jeśli rozszerzenia są skompilowane do biblioteki dll i będą się do nich odwoływały w innym zestawie.

Public Module Extensions
    ''' <summary>
    ''' Returns the version number from the specified assembly using the assembly's strong name.
    ''' </summary>
    ''' <param name="Assy">[Assembly] Assembly to get the version info from.</param>
    ''' <returns>[String]</returns>
    <Extension>
    Friend Function GetVersionFromAssembly(ByVal Assy As Assembly) As String
        Return Split(Split(Assy.FullName,",")(1),"=")(1)
    End Function
End Module


Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow