次の方法で共有


ParameterInfo.IsOptional Property

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Gets a value indicating whether this parameter is optional.

Namespace:  System.Reflection
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public ReadOnly Property IsOptional As Boolean
public bool IsOptional { get; }

Property Value

Type: System.Boolean
true if the parameter is optional; otherwise, false.

Remarks

This method depends on an optional metadata flag. This flag can be inserted by compilers, but compilers are not obligated to do so.

This method uses the Optional member of the ParameterAttributes enumeration.

To get the ParameterInfo array, first get the method, and then call MethodBase.GetParameters.

Examples

The following example shows how to test method parameters for the ParameterAttributes.Optional attribute. The example does the following:

  • Creates a dynamic assembly that contains a type named MyType.

  • Adds a static method (Shared method in Visual Basic) named MyMethod to MyType. MyMethod has an optional parameter with a default value.

  • Calls TypeBuilder.CreateType to complete the type.

  • Invokes MyMethod with no parameters to demonstrate the default value of the optional parameter.

  • Gets the parameter list for MyMethod and tests for the ParameterAttributes.In, ParameterAttributes.Out, and ParameterAttributes.Optional attributes.

Imports System.Reflection
Imports System.Reflection.Emit

Public Class Example

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      Dim myAssemblyName As New AssemblyName("MyAssembly")
      Dim myAssemblyBuilder As AssemblyBuilder = _
         AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run)
      Dim myModuleBuilder As ModuleBuilder = myAssemblyBuilder.DefineDynamicModule("MyModule")

      ' Create a type in the module.
      Dim myTypeBuilder As TypeBuilder = myModuleBuilder.DefineType("MyType", TypeAttributes.Public)

      ' Create a method called MyMethod that takes a string argument and returns a
      ' string.
      Dim myMethodBuilder As MethodBuilder = _
         myTypeBuilder.DefineMethod("MyMethod", _
            MethodAttributes.Public Or MethodAttributes.Static, _
            GetType(String), _
            New Type() { GetType(String) })

      ' Make the parameter optional, and give it a default value.
      Dim myParameterBuilder As ParameterBuilder = _
         myMethodBuilder.DefineParameter(1, _
            ParameterAttributes.Optional Or ParameterAttributes.HasDefault, "inputString")
      myParameterBuilder.SetConstant("The default value")

      ' Get the Microsoft Intermediate Language generator for the method.
      Dim myILGenerator As ILGenerator = myMethodBuilder.GetILGenerator()

      ' Get the argument and return it. When the method is called without the
      ' optional parameter, this returns the default value of the parameter.
      myILGenerator.Emit(OpCodes.Ldarg_0)
      myILGenerator.Emit(OpCodes.Ret)

      ' Create the type.
      Dim myType As Type = myTypeBuilder.CreateType()

      ' Invoke the method with no arguments, by using OptionalParamBinding. This
      ' returns the default value.
      Dim returnValue As Object = _
         myType.InvokeMember("MyMethod", _
            BindingFlags.InvokeMethod Or BindingFlags.OptionalParamBinding Or _
               BindingFlags.Static Or BindingFlags.Public, _
            Type.DefaultBinder, _
            Nothing, _
            Nothing)

      outputBlock.Text &= _
         String.Format("Calling MyMethod without the optional parameter returns: '{0}'", _
                       returnValue) & vbLf

      ' Get the method named MyMethod from the type.
      Dim myMethodBase As MethodBase = myType.GetMethod("MyMethod")


      ' Get the parameters of the method.
      Dim myParameters() As ParameterInfo = myMethodBase.GetParameters()

      outputBlock.Text &= String.Format("The method {0} has {1} parameters:" & vbLf, _
         myMethodBase, myParameters.Length)

      ' Print the IN, OUT and OPTIONAL attributes associated with each of the parameters.
      For Each param As ParameterInfo In myParameters

         If param.IsDefined(GetType(System.Runtime.InteropServices.InAttribute), False) Then
            outputBlock.Text &= _
               String.Format("    Parameter '{0}', position {1}, has the In attribute", _
                  param.Name, param.Position) & vbLf
         End If
         If param.IsOptional Then
            outputBlock.Text &= _
               String.Format("    Parameter '{0}', position {1}, has the Optional attribute", _
                  param.Name, param.Position) & vbLf
         End If
         If param.IsOut Then
            outputBlock.Text &= _
               String.Format("    Parameter '{0}', position {1}, has the Out attribute", _
                  param.Name, param.Position) & vbLf
         End If
      Next 

   End Sub 
End Class 

' This example produces the following output:
'
'Calling MyMethod without the optional parameter returns: 'The default value'
'The method System.String MyMethod(System.String) has 1 parameters:
'    Parameter 'inputString', position 0, has the Optional attribute
using System;
using System.Reflection;
using System.Reflection.Emit;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      AssemblyName myAssemblyName = new AssemblyName("MyAssembly");
      AssemblyBuilder myAssemblyBuilder = 
         AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder myModuleBuilder = 
         myAssemblyBuilder.DefineDynamicModule("MyModule");

      // Create a type in the module.
      TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("MyType", TypeAttributes.Public);

      // Create a method called MyMethod that takes a string argument and returns a
      // string.
      MethodBuilder myMethodBuilder = 
         myTypeBuilder.DefineMethod("MyMethod", 
                                    MethodAttributes.Public | MethodAttributes.Static, 
                                    typeof(string), 
                                    new Type[] { typeof(string) });

      // Make the parameter optional, and give it a default value.
      ParameterBuilder myParameterBuilder = 
         myMethodBuilder.DefineParameter(1, 
            ParameterAttributes.Optional | ParameterAttributes.HasDefault, "inputString");
      myParameterBuilder.SetConstant("The default value");

      // Get the Microsoft Intermediate Language generator for the method.
      ILGenerator myILGenerator = myMethodBuilder.GetILGenerator();

      // Get the argument and return it. When the method is called without the
      // optional parameter, this returns the default value of the parameter.
      myILGenerator.Emit(OpCodes.Ldarg_0);
      myILGenerator.Emit(OpCodes.Ret);

      // Create the type.
      Type myType = myTypeBuilder.CreateType();

      // Invoke the method with no arguments, by using OptionalParamBinding. This
      // returns the default value.
      object returnValue = myType.InvokeMember("MyMethod", 
         BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding | 
            BindingFlags.Static | BindingFlags.Public, 
         Type.DefaultBinder, 
         null, 
         null);

      outputBlock.Text += 
         String.Format("Calling MyMethod without the optional parameter returns: '{0}'\n",
         returnValue);

      // Get the method named MyMethod from the type.
      MethodBase myMethodBase = myType.GetMethod("MyMethod");


      // Get the parameters of the method.
      ParameterInfo[] myParameters = myMethodBase.GetParameters();

      outputBlock.Text += String.Format("The method {0} has {1} parameters:\n", 
         myMethodBase, myParameters.Length);

      // Print the IN, OUT and OPTIONAL attributes associated with each of the parameters.
      foreach( ParameterInfo param in myParameters )
      {
         if (param.IsDefined(typeof(System.Runtime.InteropServices.InAttribute), false))
         {
            outputBlock.Text += 
               String.Format("    Parameter '{0}', position {1}, has the In attribute\n", 
                  param.Name, param.Position);
         }
         if (param.IsOptional)
         {
            outputBlock.Text += 
               String.Format("    Parameter '{0}', position {1}, has the Optional attribute\n", 
                  param.Name, param.Position);
         }
         if (param.IsOut)
         {
            outputBlock.Text += 
               String.Format("    Parameter '{0}', position {1}, has the Out attribute\n", 
                  param.Name, param.Position);
         }
      }
   }
}

/* This example produces the following output:

Calling MyMethod without the optional parameter returns: 'The default value'
The method System.String MyMethod(System.String) has 1 parameters:
    Parameter 'inputString', position 0, has the Optional attribute
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.