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# 中,甚至可能需要使用的语言关键字和禁止使用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)

适用于

另请参阅