ParamArrayAttribute Klasa

Definicja

Wskazuje, że metoda będzie zezwalać na zmienną liczbę argumentów w wywołaniu. Klasa ta nie może być dziedziczona.

public ref class ParamArrayAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple=false, Inherited=true)]
public sealed class ParamArrayAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple=false, Inherited=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ParamArrayAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple=false, Inherited=true)>]
type ParamArrayAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple=false, Inherited=true)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ParamArrayAttribute = class
    inherit Attribute
Public NotInheritable Class ParamArrayAttribute
Inherits Attribute
Dziedziczenie
ParamArrayAttribute
Atrybuty

Przykłady

W poniższym przykładzie zdefiniowano klasę Temperature zawierającą metodę Display , która ma wyświetlać co najmniej jedną sformatowaną wartość temperatury. Metoda ma jeden parametr , formatsktóry jest zdefiniowany jako tablica parametrów.

using System;

public class Temperature
{
   private decimal temp;

   public Temperature(decimal temperature)
   {
      this.temp = temperature;
   }

   public override string ToString()
   {
      return ToString("C");
   }

   public string ToString(string format)
   {
      if (String.IsNullOrEmpty(format))
         format = "G";

      switch (format.ToUpper())
      {
         case "G":
         case "C":
            return temp.ToString("N") + "  °C";
         case "F":
            return (9 * temp / 5 + 32).ToString("N") + "  °F";
         case "K":
            return (temp + 273.15m).ToString("N") + "  °K";
         default:
            throw new FormatException(String.Format("The '{0}' format specifier is not supported",
                                                    format));
      }
   }

   public void Display(params string []formats)
   {
      if (formats.Length == 0)
      {
         Console.WriteLine(this.ToString("G"));
      }
      else
      {
         foreach (string format in formats)
         {
            try {
               Console.WriteLine(this.ToString(format));
            }
            // If there is an exception, do nothing.
            catch { }
         }
      }
   }
}
open System

type Temperature(temperature) =
    override this.ToString() =
        this.ToString "C"

    member _.ToString(format) =
        let format = 
            if String.IsNullOrEmpty format then "G"
            else format

        match format.ToUpper() with
        | "G" | "C" ->
            $"{temperature:N}  °C"
        | "F" ->
            $"{9. * temperature / 5. + 32.:N}  °F"
        | "K" ->
            $"{temperature + 273.15:N}  °K"
        | _ ->
            raise (FormatException $"The '{format}' format specifier is not supported")

    member this.Display([<ParamArray>]formats: string[]) =
        if formats.Length = 0 then
            printfn $"""{this.ToString "G"}"""
        else
            for format in formats do
                try
                    printfn $"{this.ToString format}"
                // If there is an exception, do nothing.
                with _ -> ()
Public Class Temperature 
   Private temp As Decimal
   
   Public Sub New(temperature As Decimal)
      Me.temp = temperature
   End Sub
   
   Public Overrides Function ToString() As String
      Return ToString("C")
   End Function
   
   Public Overloads Function ToString(format As String) As String
      If String.IsNullOrEmpty(format) Then format = "G"
      
      Select Case format
         Case "G", "C"
            Return temp.ToString("N") + "  °C"
         Case "F"
            Return (9 * temp / 5 + 32).ToString("N") + "  °F"
         Case "K" 
            Return (temp + 273.15d).ToString("N") + "  °K" 
         Case Else
            Throw New FormatException(String.Format("The '{0}' format specifier is not supported", _
                                                    format))
      End Select                                                         
   End Function         
   
   Public Sub Display(<[ParamArray]()> formats() As String)
      If formats.Length = 0 Then
         Console.WriteLine(Me.ToString("G"))
      Else   
         For Each format As String In formats
            Try
               Console.WriteLine(Me.ToString(format))
            ' If there is an exception, do nothing.
            Catch
            End Try   
         Next
      End If
   End Sub
End Class

Poniższy przykład ilustruje trzy różne wywołania Temperature.Display metody. W pierwszej metodzie jest przekazywana tablica ciągów formatu. W drugim metodzie są przekazywane cztery pojedyncze ciągi formatu jako argumenty. W trzecim metodzie jest wywoływana bez argumentów. Jak pokazano w danych wyjściowych z przykładu, kompilatory Visual Basic i C# przekładają to na wywołanie Display metody z pustą tablicą ciągów.

public class Class1
{
   public static void Main()
   {
      Temperature temp1 = new Temperature(100);
      string[] formats = { "C", "G", "F", "K" };

      // Call Display method with a string array.
      Console.WriteLine("Calling Display with a string array:");
      temp1.Display(formats);
      Console.WriteLine();

      // Call Display method with individual string arguments.
      Console.WriteLine("Calling Display with individual arguments:");
      temp1.Display("C", "F", "K", "G");
      Console.WriteLine();

      // Call parameterless Display method.
      Console.WriteLine("Calling Display with an implicit parameter array:");
      temp1.Display();
   }
}
// The example displays the following output:
//       Calling Display with a string array:
//       100.00  °C
//       100.00  °C
//       212.00  °F
//       373.15  °K
//
//       Calling Display with individual arguments:
//       100.00  °C
//       212.00  °F
//       373.15  °K
//       100.00  °C
//
//       Calling Display with an implicit parameter array:
//       100.00  °C
let temp1 = Temperature 100.
let formats = [| "C"; "G"; "F"; "K" |]

// Call Display method with a string array.
printfn "Calling Display with a string array:"
temp1.Display formats

// Call Display method with individual string arguments.
printfn "\nCalling Display with individual arguments:"
temp1.Display("C", "F", "K", "G")

// Call parameterless Display method.
printfn "\nCalling Display with an implicit parameter array:"
temp1.Display()
// The example displays the following output:
//       Calling Display with a string array:
//       100.00  °C
//       100.00  °C
//       212.00  °F
//       373.15  °K
//
//       Calling Display with individual arguments:
//       100.00  °C
//       212.00  °F
//       373.15  °K
//       100.00  °C
//
//       Calling Display with an implicit parameter array:
//       100.00  °C
Public Module Example
   Public Sub Main()
      Dim temp1 As New Temperature(100)
      Dim formats() As String = { "C", "G", "F", "K" } 

      ' Call Display method with a string array.
      Console.WriteLine("Calling Display with a string array:")
      temp1.Display(formats)
      Console.WriteLine()
      
      ' Call Display method with individual string arguments.
      Console.WriteLine("Calling Display with individual arguments:")
      temp1.Display("C", "F", "K", "G")
      Console.WriteLine()
      
      ' Call parameterless Display method.
      Console.WriteLine("Calling Display with an implicit parameter array:")
      temp1.Display()
   End Sub
End Module
' The example displays the following output:
'       Calling Display with a string array:
'       100.00  °C
'       100.00  °C
'       212.00  °F
'       373.15  °K
'       
'       Calling Display with individual arguments:
'       100.00  °C
'       212.00  °F
'       373.15  °K
'       100.00  °C
'       
'       Calling Display with an implicit parameter array:
'       100.00  °C

Uwagi

Wskazuje ParamArrayAttribute , że parametr metody jest tablicą parametrów. Tablica parametrów umożliwia określenie nieznanej liczby argumentów. Tablica parametrów musi być ostatnim parametrem na liście parametrów formalnych i musi być tablicą jednowymiarową. Gdy metoda jest wywoływana, tablica parametrów zezwala argumentom na określenie metody na jeden z dwóch sposobów:

  • Jako pojedyncze wyrażenie typu, który jest niejawnie konwertowany na typ tablicy parametrów. Tablica parametrów działa jako parametr wartości.

  • Jako zero lub więcej argumentów, gdzie każdy argument jest wyrażeniem typu, który jest niejawnie konwertowany na typ elementu tablicy parametrów.

W przykładzie w następnej sekcji przedstawiono obie konwencje wywoływania.

Uwaga

Zazwyczaj element ParamArrayAttribute nie jest używany bezpośrednio w kodzie. Zamiast tego poszczególne słowa kluczowe języka, takie jak ParamArray w Visual Basic i params C#, są używane jako otoki dla ParamArrayAttribute klasy. Niektóre języki, takie jak C#, mogą nawet wymagać użycia słowa kluczowego języka i uniemożliwić użycie elementu ParamArrayAttribute.

Podczas rozwiązywania przeciążeń, gdy kompilatory obsługujące tablice parametrów napotykają przeciążenie metody, które nie istnieje, ale ma jedną mniej parametrów niż przeciążenie zawierające tablicę parametrów, zastąpią metodę przeciążeniem zawierającym tablicę parametrów. Na przykład wywołanie String.Split() metody wystąpienia (która nie istnieje w String klasie) jest rozpoznawane jako wywołanie String.Split(Char[]) metody . Kompilator przekaże również pustą tablicę wymaganego typu do metody . Oznacza to, że metoda musi być zawsze przygotowana do obsługi tablicy, której długość wynosi zero, gdy przetwarza elementy w tablicy parametrów. Przykład stanowi ilustrację.

Aby uzyskać więcej informacji na temat używania atrybutów, zobacz Atrybuty.

Konstruktory

ParamArrayAttribute()

Inicjuje ParamArrayAttribute nowe wystąpienie klasy z domyślnymi właściwościami.

Właściwości

TypeId

Po zaimplementowaniu w klasie pochodnej pobiera unikatowy identyfikator dla tego Attributeelementu .

(Odziedziczone po Attribute)

Metody

Equals(Object)

Zwraca wartość wskazującą, czy to wystąpienie jest równe podanemu obiektowi.

(Odziedziczone po Attribute)
GetHashCode()

Zwraca wartość skrótu dla tego wystąpienia.

(Odziedziczone po Attribute)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
IsDefaultAttribute()

W przypadku zastąpienia w klasie pochodnej wskazuje, czy wartość tego wystąpienia jest wartością domyślną klasy pochodnej.

(Odziedziczone po Attribute)
Match(Object)

Po przesłonięciu w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

(Odziedziczone po Attribute)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Zestaw nazw jest mapowany na odpowiedni zestaw identyfikatorów wysyłania.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Pobiera informacje o typie dla obiektu, który może służyć do pobierania informacji o typie dla interfejsu.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Pobiera informację o liczbie typów interfejsów, jakie zawiera obiekt (0 lub 1).

(Odziedziczone po Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Umożliwia dostęp do właściwości i metod udostępnianych przez obiekt.

(Odziedziczone po Attribute)

Dotyczy

Zobacz też