共用方式為


MethodBuilder.DefineGenericParameters Method

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

Sets the number of generic type parameters for the current method, specifies their names, and returns an array of GenericTypeParameterBuilder objects that can be used to define their constraints.

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

Syntax

'Declaration
Public Function DefineGenericParameters ( _
    ParamArray names As String() _
) As GenericTypeParameterBuilder()
public GenericTypeParameterBuilder[] DefineGenericParameters(
    params string[] names
)

Parameters

  • names
    Type: array<System.String[]
    An array of strings that represent the names of the generic type parameters.

Return Value

Type: array<System.Reflection.Emit.GenericTypeParameterBuilder[]
An array of GenericTypeParameterBuilder objects representing the type parameters of the generic method.

Exceptions

Exception Condition
InvalidOperationException

Generic type parameters have already been defined for this method.

-or-

The method has been completed already.

-or-

The SetImplementationFlags method has been called for the current method.

ArgumentNullException

names is nulla null reference (Nothing in Visual Basic).

-or-

An element of names is nulla null reference (Nothing in Visual Basic).

ArgumentException

names is an empty array.

Remarks

Calling the DefineGenericParameters method makes the current method generic. There is no way to undo this change. Calling this method a second time causes an InvalidOperationException.

The type parameters of the generic method can be retrieved later by using the GetGenericArguments method.

By convention, a type parameter name is a single uppercase letter.

For more information, see MethodInfo.IsGenericMethod and MethodInfo.GetGenericMethodDefinition. For information on generic types, see Type.IsGenericType.

Examples

The following example creates a dynamic type, DemoType, which contains the dynamic generic method DemoMethod. This method has two generic type parameters, one of which is used as a parameter and the other as the return type.

NoteNote:

This code example generates a simple method body that merely returns a null reference. For a code example with a more fully developed method body that creates and uses generic types, see How to: Define a Generic Method with Reflection Emit.

Imports System.Reflection
Imports System.Reflection.Emit

Class Example

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      ' Creating a dynamic assembly requires an AssemblyName
      ' object, and the current application domain.
      '
      Dim asmName As New AssemblyName("Example1")
      Dim domain As AppDomain = AppDomain.CurrentDomain
      Dim demoAssembly As AssemblyBuilder = _
          domain.DefineDynamicAssembly(asmName, _
              AssemblyBuilderAccess.Run)
      Dim demoModule As ModuleBuilder = _
          demoAssembly.DefineDynamicModule( _
              asmName.Name)

      Dim demoType As TypeBuilder = demoModule.DefineType( _
          "DemoType", _
          TypeAttributes.Public Or TypeAttributes.Abstract)

      ' Define a Shared, Public method with standard calling
      ' conventions. Do not specify the parameter types or the
      ' return type, because type parameters will be used for 
      ' those types, and the type parameters have not been
      ' defined yet.
      Dim demoMethod As MethodBuilder = _
          demoType.DefineMethod("DemoMethod", _
              MethodAttributes.Public Or MethodAttributes.Static)

      ' Defining generic parameters for the method makes it a
      ' generic method. By convention, type parameters are 
      ' single alphabetic characters. T and U are used here.
      '
      Dim typeParamNames() As String = {"T", "U"}
      Dim typeParameters() As GenericTypeParameterBuilder = _
          demoMethod.DefineGenericParameters(typeParamNames)

      ' The second type parameter is constrained to be a 
      ' reference type.
      typeParameters(1).SetGenericParameterAttributes( _
          GenericParameterAttributes.ReferenceTypeConstraint)

      ' Use the IsGenericMethod property to find out if a
      ' dynamic method is generic, and IsGenericMethodDefinition
      ' to find out if it defines a generic method.
      outputBlock.Text &= String.Format("Is DemoMethod generic? {0}", _
          demoMethod.IsGenericMethod) & vbCrLf
      outputBlock.Text &= String.Format("Is DemoMethod a generic method definition? {0}", _
          demoMethod.IsGenericMethodDefinition) & vbCrLf

      ' Set parameter types for the method. The method takes
      ' one parameter, and its type is specified by the first
      ' type parameter, T.
      Dim params() As Type = {typeParameters(0)}
      demoMethod.SetParameters(params)

      ' Set the return type for the method. The return type is
      ' specified by the second type parameter, U.
      demoMethod.SetReturnType(typeParameters(1))

      ' Generate a code body for the method. The method doesn't
      ' do anything except return Nothing.
      '
      Dim ilgen As ILGenerator = demoMethod.GetILGenerator()
      ilgen.Emit(OpCodes.Ldnull)
      ilgen.Emit(OpCodes.Ret)

      ' Complete the type.
      Dim dt As Type = demoType.CreateType()

      ' To bind types to a dynamic generic method, you must 
      ' first call the GetMethod method on the completed type.
      ' You can then define an array of types, and bind them
      ' to the method.
      Dim m As MethodInfo = dt.GetMethod("DemoMethod")
      Dim typeArgs() As Type = _
          {GetType(String), GetType(Example)}
      Dim bound As MethodInfo = m.MakeGenericMethod(typeArgs)
      ' Display a string representing the bound method.
      outputBlock.Text &= bound.ToString() & vbCrLf
   End Sub
End Class

' This code example produces the following output:
'Is DemoMethod generic? True
'Is DemoMethod a generic method definition? True
'DemoMethodBuilder DemoMethod[String,DemoMethodBuilder](System.String)
using System;
using System.Reflection;
using System.Reflection.Emit;

class Example
{

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Creating a dynamic assembly requires an AssemblyName
      // object, and the current application domain.
      //
      AssemblyName asmName =
          new AssemblyName("Example1");
      AppDomain domain = AppDomain.CurrentDomain;
      AssemblyBuilder demoAssembly =
          domain.DefineDynamicAssembly(
              asmName,
              AssemblyBuilderAccess.Run
          );
      ModuleBuilder demoModule =
          demoAssembly.DefineDynamicModule(
              asmName.Name
          );

      TypeBuilder demoType = demoModule.DefineType(
          "DemoType",
          TypeAttributes.Public | TypeAttributes.Abstract
      );

      // Define a Shared, Public method with standard calling
      // conventions. Do not specify the parameter types or the
      // return type, because type parameters will be used for 
      // those types, and the type parameters have not been
      // defined yet.
      MethodBuilder demoMethod = demoType.DefineMethod(
          "DemoMethod",
          MethodAttributes.Public | MethodAttributes.Static
      );

      // Defining generic parameters for the method makes it a
      // generic method. By convention, type parameters are 
      // single alphabetic characters. T and U are used here.
      //
      string[] typeParamNames = { "T", "U" };
      GenericTypeParameterBuilder[] typeParameters =
          demoMethod.DefineGenericParameters(typeParamNames);

      // The second type parameter is constrained to be a 
      // reference type.
      typeParameters[1].SetGenericParameterAttributes(
          GenericParameterAttributes.ReferenceTypeConstraint);

      // Use the IsGenericMethod property to find out if a
      // dynamic method is generic, and IsGenericMethodDefinition
      // to find out if it defines a generic method.
      outputBlock.Text += String.Format("Is DemoMethod generic? {0}",
          demoMethod.IsGenericMethod) + "\n";
      outputBlock.Text += String.Format("Is DemoMethod a generic method definition? {0}",
          demoMethod.IsGenericMethodDefinition) + "\n";

      // Set parameter types for the method. The method takes
      // one parameter, and its type is specified by the first
      // type parameter, T.
      Type[] parms = { typeParameters[0] };
      demoMethod.SetParameters(parms);

      // Set the return type for the method. The return type is
      // specified by the second type parameter, U.
      demoMethod.SetReturnType(typeParameters[1]);

      // Generate a code body for the method. The method doesn't
      // do anything except return null.
      //
      ILGenerator ilgen = demoMethod.GetILGenerator();
      ilgen.Emit(OpCodes.Ldnull);
      ilgen.Emit(OpCodes.Ret);

      // Complete the type.
      Type dt = demoType.CreateType();

      // To bind types to a dynamic generic method, you must 
      // first call the GetMethod method on the completed type.
      // You can then define an array of types, and bind them
      // to the method.
      MethodInfo m = dt.GetMethod("DemoMethod");
      Type[] typeArgs = { typeof(string), typeof(Example) };
      MethodInfo bound = m.MakeGenericMethod(typeArgs);
      // Display a string representing the bound method.
      outputBlock.Text += bound.ToString() + "\n";
   }
}

/* This code example produces the following output:
Is DemoMethod generic? True
Is DemoMethod a generic method definition? True
DemoMethodBuilder DemoMethod[String,DemoMethodBuilder](System.String)
*/

Version Information

Silverlight

Supported in: 5, 4, 3

Platforms

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