ParamArrayAttribute Класс

Определение

Указывает, что метод может быть вызван с переменным числом аргументов. Этот класс не наследуется.

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
Наследование
ParamArrayAttribute
Атрибуты

Примеры

В следующем примере определяется Temperature класс, включающий метод , предназначенный Display для отображения одного или нескольких форматированных значений температуры. Метод имеет один параметр , formatsкоторый определен как массив параметров.

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

В следующем примере показаны три разных вызова Temperature.Display метода . В первом методу передается массив строк формата. Во втором метод передает четыре отдельные строки формата в качестве аргументов. В третьем метод вызывается без аргументов. Как показано в выходных данных из примера, компиляторы Visual Basic и C# преобразуют это в вызов Display метода с пустым строковым массивом.

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

Комментарии

Указывает ParamArrayAttribute , что параметр метода является массивом параметров. Массив параметров позволяет указать неизвестное число аргументов. Массив параметров должен быть последним параметром в формальном списке параметров и одномерным массивом. При вызове метода массив параметров позволяет указать аргументы метода двумя способами:

  • Как отдельное выражение типа, которое неявно можно преобразовать в тип массива параметров. Массив параметров функционирует как параметр значения.

  • Как ноль или более аргументов, где каждый аргумент является выражением типа, который неявно можно преобразовать в тип элемента массива параметров.

В примере в следующем разделе показаны оба соглашения о вызовах.

Примечание

Как правило, ParamArrayAttribute объект не используется непосредственно в коде. Вместо этого в качестве оболочек для ParamArrayAttribute класса используются ключевые слова отдельных языков, например ParamArray в Visual Basic и params C#. Некоторые языки, например C#, могут даже требовать использования ключевого слова языка и запрещать использование ParamArrayAttribute.

При разрешении перегрузки, когда компиляторы, поддерживающие массивы параметров, сталкиваются с перегрузкой метода, которая не существует, но имеет на один параметр меньше, чем перегрузка, включающая массив параметров, они заменяют метод перегрузкой, включающей массив параметров. Например, вызов метода экземпляра String.Split() (который не существует в String классе) разрешается как вызов String.Split(Char[]) метода . Компилятор также передает в метод пустой массив требуемого типа. Это означает, что метод всегда должен быть подготовлен к обработке массива, длина которого равна нулю при обработке элементов в массиве параметров. Иллюстрация приведена в примере.

Дополнительные сведения об использовании атрибутов см. в разделе Атрибуты.

Конструкторы

ParamArrayAttribute()

Инициализирует новый экземпляр класса ParamArrayAttribute стандартными свойствами.

Свойства

TypeId

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute.

(Унаследовано от Attribute)

Методы

Equals(Object)

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

(Унаследовано от Attribute)
GetHashCode()

Возвращает хэш-код данного экземпляра.

(Унаследовано от Attribute)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

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

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта.

(Унаследовано от Attribute)

Применяется к

См. также раздел