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
- Наследование
- Атрибуты
Примеры
В следующем примере определяется 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 , что параметр метода является массивом параметров. Массив параметров позволяет определить неизвестное число аргументов. Массив параметров должен быть последним параметром в формальном списке параметров, и он должен быть массивом с одним измерением. При вызове метода массив параметров разрешает аргументы методу указываться двумя способами:
Как одно выражение типа, который неявно преобразуется в тип массива параметров. Массив параметров функционирует как параметр значения.
В качестве нулевых или более аргументов, где каждый аргумент является выражением типа, который неявно преобразуется в тип элемента массива параметров.
В примере в следующем разделе показаны оба соглашения о вызовах.
Note
Как правило, он ParamArrayAttribute не используется непосредственно в коде. Вместо этого отдельные ключевые слова языка, такие как ParamArray в Visual Basic и params в C#, используются в качестве оболочки для класса ParamArrayAttribute. Некоторые языки, такие как 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) |