ParamArrayAttribute ParamArrayAttribute ParamArrayAttribute ParamArrayAttribute Class

定义

指示方法在调用中将允许参数的数目可变。Indicates that a method will allow a variable number of arguments in its invocation. 此类不能被继承。This class cannot be inherited.

public ref class ParamArrayAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple=false, Inherited=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ParamArrayAttribute : Attribute
type ParamArrayAttribute = class
    inherit Attribute
Public NotInheritable Class ParamArrayAttribute
Inherits Attribute
继承
ParamArrayAttributeParamArrayAttributeParamArrayAttributeParamArrayAttribute
属性

示例

下面的示例定义一个Temperature Display包含方法的类, 该方法旨在显示一个或多个格式化的温度值。The following example defines a Temperature class that includes a Display method, which is intended to display one or more formatted temperature values. 方法具有一个参数, formats该参数定义为参数数组。The method has a single parameter, formats, which is defined as a parameter array.

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 { }
         }
      }
   }
}
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三个不同调用。The following example illustrates three different calls to the Temperature.Display method. 在第一种方法中, 向方法传递格式字符串数组。In the first, the method is passed an array of format strings. 在第二个中, 方法将四个单独的格式字符串作为参数传递。In the second, the method is passed four individual format strings as arguments. 在第三种情况下, 不带参数调用方法。In the third, the method is called with no arguments. 如示例的输出所示, Visual Basic 和C#编译器会将其转换为具有空字符串数组Display的方法调用。As the output from the example illustrates, the Visual Basic and C# compilers translate this into a call to the Display method with an empty string array.

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
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指示方法参数是参数数组。The ParamArrayAttribute indicates that a method parameter is a parameter array. 参数数组允许指定数量未知的参数。A parameter array allows the specification of an unknown number of arguments. 参数数组必须是形参表中的最后一个形参, 并且必须是一维数组。A parameter array must be the last parameter in a formal parameter list, and it must be a single-dimension array. 调用方法时, 参数数组允许使用以下两种方法之一来指定方法的参数:When the method is called, a parameter array permits arguments to a method to be specified in either of two ways:

  • 作为可隐式转换为参数数组类型的类型的单个表达式。As a single expression of a type that is implicitly convertible to the parameter array type. 参数数组作为值参数。The parameter array functions as a value parameter.

  • 作为零个或多个参数, 其中每个参数都是可隐式转换为参数数组元素类型的类型的表达式。As zero or more arguments, where each argument is an expression of a type that is implicitly convertible to the type of the parameter array element.

下一节中的示例说明了这两种调用约定。The example in the next section illustrates both calling conventions.

备注

通常, ParamArrayAttribute不会直接在代码中使用。Typically, the ParamArrayAttribute is not used directly in code. 相反, 各语言ParamArray关键字 (如 Visual Basic 和params中C#的) 用作类的ParamArrayAttribute包装。Instead, individual language keywords, such as ParamArray in Visual Basic and params in C#, are used as wrappers for the ParamArrayAttribute class. 某些语言 (例如C#) 甚至可能需要使用 language 关键字, 禁止使用。 ParamArrayAttributeSome languages, such as C#, may even require the use of the language keyword and prohibit the use of ParamArrayAttribute.

在重载解析过程中, 当支持参数数组的编译器遇到不存在但其参数比包含参数数组的重载少一个的方法重载时, 它们会将方法替换为包含参数数组。During overload resolution, when compilers that support parameter arrays encounter a method overload that does not exist but has one fewer parameter than an overload that includes a parameter array, they will replace the method with the overload that includes the parameter array. 例如, 对String.Split()实例方法 ( String该类中不存在) 的调用被解析String.Split(Char[])为对方法的调用。For example, a call to the String.Split() instance method (which does not exist in the String class) is resolved as a call to the String.Split(Char[]) method. 编译器还会将所需类型的空数组传递给方法。The compiler will also pass an empty array of the required type to the method. 这意味着, 在处理参数数组中的元素时, 该方法必须始终准备好处理长度为零的数组。This means that the method must always be prepared to handle an array whose length is zero when it processes the elements in the parameter array. 说明如示例所示。The example provides an illustration.

有关使用特性的详细信息, 请参阅特性For more information about using attributes, see Attributes.

构造函数

ParamArrayAttribute() ParamArrayAttribute() ParamArrayAttribute() ParamArrayAttribute()

使用默认属性初始化 ParamArrayAttribute 类的新实例。Initializes a new instance of the ParamArrayAttribute class with default properties.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

在派生类中重写时,指示此实例的值是否是派生类的默认值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

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

将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

属性

TypeId TypeId TypeId TypeId

在派生类中实现时,获取此 Attribute 的唯一标识符。When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

适用于

另请参阅