MethodBuilder.SetSignature(Type, Type[], Type[], Type[], Type[][], Type[][]) 方法

定义

设置方法签名,包括返回类型、参数类型以及返回类型和参数类型所需和可选的自定义修饰符。Sets the method signature, including the return type, the parameter types, and the required and optional custom modifiers of the return type and parameter types.

public:
 void SetSignature(Type ^ returnType, cli::array <Type ^> ^ returnTypeRequiredCustomModifiers, cli::array <Type ^> ^ returnTypeOptionalCustomModifiers, cli::array <Type ^> ^ parameterTypes, cli::array <cli::array <Type ^> ^> ^ parameterTypeRequiredCustomModifiers, cli::array <cli::array <Type ^> ^> ^ parameterTypeOptionalCustomModifiers);
public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers);
member this.SetSignature : Type * Type[] * Type[] * Type[] * Type[][] * Type[][] -> unit
Public Sub SetSignature (returnType As Type, returnTypeRequiredCustomModifiers As Type(), returnTypeOptionalCustomModifiers As Type(), parameterTypes As Type(), parameterTypeRequiredCustomModifiers As Type()(), parameterTypeOptionalCustomModifiers As Type()())

参数

returnType
Type

方法的返回类型。The return type of the method.

returnTypeRequiredCustomModifiers
Type[]

一个类型数组,表示该方法的返回类型所必需的自定义修饰符,如 IsConstAn array of types representing the required custom modifiers, such as IsConst, for the return type of the method. 如果返回类型没有所需的自定义修饰符,则指定 nullIf the return type has no required custom modifiers, specify null.

returnTypeOptionalCustomModifiers
Type[]

一个类型数组,表示该方法的返回类型的可选自定义修饰符,如 IsConstAn array of types representing the optional custom modifiers, such as IsConst, for the return type of the method. 如果返回类型没有可选的自定义修饰符,则指定 nullIf the return type has no optional custom modifiers, specify null.

parameterTypes
Type[]

方法参数的类型。The types of the parameters of the method.

parameterTypeRequiredCustomModifiers
Type[][]

由类型数组组成的数组。An array of arrays of types. 每个类型数组均表示相应参数所必需的自定义修饰符,如 IsConstEach array of types represents the required custom modifiers for the corresponding parameter, such as IsConst. 如果某个特定参数没有所需的自定义修饰符,则指定 null,而不要指定类型数组。If a particular parameter has no required custom modifiers, specify null instead of an array of types. 如果所有参数都没有所需的自定义修饰符,则指定 null,而不要指定由数组组成的数组。If none of the parameters have required custom modifiers, specify null instead of an array of arrays.

parameterTypeOptionalCustomModifiers
Type[][]

由类型数组组成的数组。An array of arrays of types. 每个类型数组均表示相应参数的可选自定义修饰符,如 IsConstEach array of types represents the optional custom modifiers for the corresponding parameter, such as IsConst. 如果某个特定参数没有可选的自定义修饰符,则指定 null,而不要指定类型数组。If a particular parameter has no optional custom modifiers, specify null instead of an array of types. 如果所有参数都没有可选的自定义修饰符,则指定 null,而不要指定由数组组成的数组。If none of the parameters have optional custom modifiers, specify null instead of an array of arrays.

异常

当前方法是泛型方法,但不是泛型方法定义。The current method is generic, but is not a generic method definition. 也就是说,属性 IsGenericMethodtrue,但属性 IsGenericMethodDefinitionfalseThat is, the IsGenericMethod property is true, but the IsGenericMethodDefinition property is false.

示例

下面的代码示例包含一个名为 Sample T的泛型类的源代码。The following code example contains source code for a generic class named Sample that has a type parameter T. 类具有一个名为 Field、类型为 T的字段,以及一个具有其自己的类型参数 U的泛型方法 GMThe class has a field named Field, of type T, and a generic method GM with its own type parameter, U. 方法 GM 创建示例的实例,将其自己的类型参数替换为 Sample 的类型参数 U,并将其输入参数存储在 Field中。Method GM creates an instance of Sample, substituting its own type parameter U for the type parameter of Sample, and stores its input parameter in Field. 已编译但未使用此源代码;可以使用Ildasm (IL 拆装器)查看它,并将其与类 Example所发出的代码进行比较。This source code is compiled but not used; you can view it with the Ildasm.exe (IL Disassembler), and compare it to the code emitted by class Example.

Example 中的代码演示如何使用发出泛型代码的 SetSignature 方法。The code in class Example demonstrates the use of the SetSignature method in emitting generic code. ExampleMain 方法创建一个包含名为 Sample的类的动态程序集,并使用 TypeBuilder.DefineGenericParameters 方法通过添加一个名为 T的类型参数使其成为泛型。The Main method of class Example creates a dynamic assembly containing a class named Sample, and uses the TypeBuilder.DefineGenericParameters method to make it generic by adding a type parameter named T. T类型的无参数构造函数和名为 Field的字段将添加到类 SampleA parameterless constructor and a field named Field, of type T, are added to class Sample. 使用 DefineGenericParameters 方法添加了方法 GM,并将其转换为泛型方法。A method GM is added, and turned into a generic method using the DefineGenericParameters method. GM 的类型参数名为 UThe type parameter of GM is named U. 定义类型参数后,将使用 SetSignature 方法添加 GM 的签名。Once the type parameter is defined, the signature of GM is added, using the SetSignature method. 没有返回类型,并且没有必需的修饰符或自定义修饰符,因此,此方法的所有参数都是 null 除了 parameterTypes,后者用于设置方法的唯一参数的类型;此参数设置为方法的类型参数,UThere is no return type, and no required or custom modifiers, so all the parameters of this method are null except parameterTypes, which sets the type of the only parameter of the method; this is set to the method's type parameter, U. 方法的主体创建构造类型的实例 Sample<U>Sample(Of U) 在 Visual Basic 中),将该方法的参数分配给 Field,然后打印 Field的值。The body of the method creates an instance of the constructed type Sample<U> (Sample(Of U) in Visual Basic), assigns the method's parameter to Field, and then prints the value of Field. 定义了一个虚拟类型,用于保存入口点方法 MainA dummy type is defined, to hold the entry point method Main. Main的主体中,将在构造的泛型类型 Sample<int>Sample(Of Integer) 中的 Visual Basic)中调用静态 GM 方法,并将类型 String 替换为 UIn the body of Main, the static GM method is invoked on the constructed generic type Sample<int> (Sample(Of Integer) in Visual Basic), with type String substituted for U. TypeBuilder.GetMethod 方法用于为构造的泛型类型 Sample<U>的静态 GM 方法创建 MethodInfo,然后使用 MethodInfo.MakeGenericMethod 方法创建可在方法调用中发出的 MethodInfoThe TypeBuilder.GetMethod method is used to create a MethodInfo for the static GM method of the constructed generic type Sample<U>, and the MethodInfo.MakeGenericMethod method is then used to create a MethodInfo that can emitted in a method call.

运行代码示例时,它会将发出的程序集保存为 TypeBuilderGetFieldExample。When the code example is run, it saves the emitted assembly as TypeBuilderGetFieldExample.exe. 您可以运行 TypeBuilderGetFieldExample,并且可以使用Ildasm (IL 拆装器)将发出的代码与编译为代码示例本身的 Sample 类的代码进行比较。You can run TypeBuilderGetFieldExample.exe, and you can use the Ildasm.exe (IL Disassembler) to compare the emitted code with the code for the Sample class that is compiled into the code example itself.

using System;
using System.Reflection;
using System.Reflection.Emit;

// Compare the MSIL in this class to the MSIL
// generated by the Reflection.Emit code in class
// Example.
public class Sample<T>
{
  public T Field;
  public static void GM<U>(U val)
  {
    Sample<U> s = new Sample<U>();
    s.Field = val;
    Console.WriteLine(s.Field);
  }
}

public class Example
{
    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName myAsmName = 
            new AssemblyName("TypeBuilderGetFieldExample");
        AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(
            myAsmName, AssemblyBuilderAccess.Save);
        ModuleBuilder myModule = myAssembly.DefineDynamicModule(
            myAsmName.Name, 
            myAsmName.Name + ".exe");

        // Define the sample type.
        TypeBuilder myType = myModule.DefineType("Sample", 
            TypeAttributes.Class | TypeAttributes.Public);

        // Add a type parameter, making the type generic.
        string[] typeParamNames = {"T"};  
        GenericTypeParameterBuilder[] typeParams = 
            myType.DefineGenericParameters(typeParamNames);

        // Define a default constructor. Normally it would 
        // not be necessary to define the default constructor,
        // but in this case it is needed for the call to
        // TypeBuilder.GetConstructor, which gets the default
        // constructor for the generic type constructed from 
        // Sample<T>, in the generic method GM<U>.
        ConstructorBuilder ctor = myType.DefineDefaultConstructor(
            MethodAttributes.PrivateScope | MethodAttributes.Public |
            MethodAttributes.HideBySig | MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName);

        // Add a field of type T, with the name Field.
        FieldBuilder myField = myType.DefineField("Field", 
            typeParams[0],
            FieldAttributes.Public);

        // Add a method and make it generic, with a type 
        // parameter named U. Note how similar this is to 
        // the way Sample is turned into a generic type. The
        // method has no signature, because the type of its
        // only parameter is U, which is not yet defined.
        MethodBuilder genMethod = myType.DefineMethod("GM", 
            MethodAttributes.Public | MethodAttributes.Static);
        string[] methodParamNames = {"U"};
        GenericTypeParameterBuilder[] methodParams = 
            genMethod.DefineGenericParameters(methodParamNames);
        
        // Now add a signature for genMethod, specifying U
        // as the type of the parameter. There is no return value
        // and no custom modifiers.
        genMethod.SetSignature(null, null, null, 
            new Type[] { methodParams[0] }, null, null);

        // Emit a method body for the generic method.
        ILGenerator ilg = genMethod.GetILGenerator();
        // Construct the type Sample<U> using MakeGenericType.
        Type SampleOfU = myType.MakeGenericType( methodParams[0] );
        // Create a local variable to store the instance of
        // Sample<U>.
        ilg.DeclareLocal(SampleOfU);
        // Call the default constructor. Note that it is 
        // necessary to have the default constructor for the
        // constructed generic type Sample<U>; use the 
        // TypeBuilder.GetConstructor method to obtain this 
        // constructor.
        ConstructorInfo ctorOfU = TypeBuilder.GetConstructor(
            SampleOfU, ctor);
        ilg.Emit(OpCodes.Newobj, ctorOfU);
        // Store the instance in the local variable; load it
        // again, and load the parameter of genMethod.
        ilg.Emit(OpCodes.Stloc_0); 
        ilg.Emit(OpCodes.Ldloc_0); 
        ilg.Emit(OpCodes.Ldarg_0);
        // In order to store the value in the field of the
        // instance of Sample<U>, it is necessary to have 
        // a FieldInfo representing the field of the 
        // constructed type. Use TypeBuilder.GetField to 
        // obtain this FieldInfo.
        FieldInfo FieldOfU = TypeBuilder.GetField(
            SampleOfU, myField);
        // Store the value in the field. 
        ilg.Emit(OpCodes.Stfld, FieldOfU);
        // Load the instance, load the field value, box it
        // (specifying the type of the type parameter, U), and
        // print it.
        ilg.Emit(OpCodes.Ldloc_0);
        ilg.Emit(OpCodes.Ldfld, FieldOfU);
        ilg.Emit(OpCodes.Box, methodParams[0]);
        MethodInfo writeLineObj = 
            typeof(Console).GetMethod("WriteLine", 
                new Type[] { typeof(object) });
        ilg.EmitCall(OpCodes.Call, writeLineObj, null);
        ilg.Emit(OpCodes.Ret);

        // Emit an entry point method; this must be in a
        // non-generic type.
        TypeBuilder dummy = myModule.DefineType("Dummy", 
            TypeAttributes.Class | TypeAttributes.NotPublic);
        MethodBuilder entryPoint = dummy.DefineMethod("Main", 
            MethodAttributes.Public | MethodAttributes.Static,
            null, null);
        ilg = entryPoint.GetILGenerator();
        // In order to call the static generic method GM, it is
        // necessary to create a constructed type from the 
        // generic type definition for Sample. This can be any
        // constructed type; in this case Sample<int> is used.
        Type SampleOfInt = 
            myType.MakeGenericType( typeof(int) );
        // Next get a MethodInfo representing the static generic
        // method GM on type Sample<int>.
        MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt, 
            genMethod);
        // Next get a MethodInfo for GM<string>, which is the 
        // instantiation of GM that Main calls.
        MethodInfo GMOfString = 
            SampleOfIntGM.MakeGenericMethod( typeof(string) );
        // Finally, emit the call. Push a string onto
        // the stack, as the argument for the generic method.
        ilg.Emit(OpCodes.Ldstr, "Hello, world!");
        ilg.EmitCall(OpCodes.Call, GMOfString, null);
        ilg.Emit(OpCodes.Ret);

        myType.CreateType();
        dummy.CreateType();
        myAssembly.SetEntryPoint(entryPoint);
        myAssembly.Save(myAsmName.Name + ".exe");

        Console.WriteLine(myAsmName.Name + ".exe has been saved.");
    }
}
Imports System.Reflection
Imports System.Reflection.Emit

' Compare the MSIL in this class to the MSIL
' generated by the Reflection.Emit code in class
' Example.
Public Class Sample(Of T)
    Public Field As T
    Public Shared Sub GM(Of U)(ByVal val As U)
        Dim s As New Sample(Of U)
        s.Field = val
        Console.WriteLine(s.Field)
    
    End Sub
End Class 

Public Class Example
    
    Public Shared Sub Main() 
        Dim myDomain As AppDomain = AppDomain.CurrentDomain
        Dim myAsmName As New AssemblyName("TypeBuilderGetFieldExample")
        Dim myAssembly As AssemblyBuilder = _
            myDomain.DefineDynamicAssembly(myAsmName, _
                AssemblyBuilderAccess.Save)
        Dim myModule As ModuleBuilder = _
            myAssembly.DefineDynamicModule(myAsmName.Name, _
                myAsmName.Name & ".exe")
        
        ' Define the sample type.
        Dim myType As TypeBuilder = myModule.DefineType( _
            "Sample", _
            TypeAttributes.Class Or TypeAttributes.Public)
        
        ' Add a type parameter, making the type generic.
        Dim typeParamNames() As String = { "T" }
        Dim typeParams As GenericTypeParameterBuilder() = _
            myType.DefineGenericParameters(typeParamNames)
        
        ' Define a default constructor. Normally it would 
        ' not be necessary to define the default constructor,
        ' but in this case it is needed for the call to
        ' TypeBuilder.GetConstructor, which gets the default
        ' constructor for the generic type constructed from 
        ' Sample(Of T), in the generic method GM(Of U).
        Dim ctor As ConstructorBuilder = _
            myType.DefineDefaultConstructor( _
                MethodAttributes.PrivateScope Or MethodAttributes.Public _
                Or MethodAttributes.HideBySig Or MethodAttributes.SpecialName _
                Or MethodAttributes.RTSpecialName)
        
        ' Add a field of type T, with the name Field.
        Dim myField As FieldBuilder = myType.DefineField( _
            "Field", typeParams(0), FieldAttributes.Public)
        
        ' Add a method and make it generic, with a type 
        ' parameter named U. Note how similar this is to 
        ' the way Sample is turned into a generic type. The
        ' method has no signature, because the type of its
        ' only parameter is U, which is not yet defined.
        Dim genMethod As MethodBuilder = _
            myType.DefineMethod("GM", _
                MethodAttributes.Public Or MethodAttributes.Static)
        Dim methodParamNames() As String = { "U" }
        Dim methodParams As GenericTypeParameterBuilder() = _
            genMethod.DefineGenericParameters(methodParamNames)

        ' Now add a signature for genMethod, specifying U
        ' as the type of the parameter. There is no return value
        ' and no custom modifiers.
        genMethod.SetSignature(Nothing, Nothing, Nothing, _
            New Type() { methodParams(0) }, Nothing, Nothing)
        
        ' Emit a method body for the generic method.
        Dim ilg As ILGenerator = genMethod.GetILGenerator()
        ' Construct the type Sample(Of U) using MakeGenericType.
        Dim SampleOfU As Type = _
            myType.MakeGenericType(methodParams(0))
        ' Create a local variable to store the instance of
        ' Sample(Of U).
        ilg.DeclareLocal(SampleOfU)
        ' Call the default constructor. Note that it is 
        ' necessary to have the default constructor for the
        ' constructed generic type Sample(Of U); use the 
        ' TypeBuilder.GetConstructor method to obtain this 
        ' constructor.
        Dim ctorOfU As ConstructorInfo = _
            TypeBuilder.GetConstructor(SampleOfU, ctor)
        ilg.Emit(OpCodes.Newobj, ctorOfU)
        ' Store the instance in the local variable; load it
        ' again, and load the parameter of genMethod.
        ilg.Emit(OpCodes.Stloc_0)
        ilg.Emit(OpCodes.Ldloc_0)
        ilg.Emit(OpCodes.Ldarg_0)
        ' In order to store the value in the field of the
        ' instance of Sample(Of U), it is necessary to have 
        ' a FieldInfo representing the field of the 
        ' constructed type. Use TypeBuilder.GetField to 
        ' obtain this FieldInfo.
        Dim FieldOfU As FieldInfo = _
            TypeBuilder.GetField(SampleOfU, myField)
        ' Store the value in the field. 
        ilg.Emit(OpCodes.Stfld, FieldOfU)
        ' Load the instance, load the field value, box it
        ' (specifying the type of the type parameter, U), 
        ' and print it.
        ilg.Emit(OpCodes.Ldloc_0)
        ilg.Emit(OpCodes.Ldfld, FieldOfU)
        ilg.Emit(OpCodes.Box, methodParams(0))
        Dim writeLineObj As MethodInfo = _
            GetType(Console).GetMethod("WriteLine", _
                New Type() {GetType(Object)})
        ilg.EmitCall(OpCodes.Call, writeLineObj, Nothing)
        ilg.Emit(OpCodes.Ret)
        
        ' Emit an entry point method; this must be in a
        ' non-generic type.
        Dim dummy As TypeBuilder = _
            myModule.DefineType("Dummy", _
                TypeAttributes.Class Or TypeAttributes.NotPublic)
        Dim entryPoint As MethodBuilder = _
            dummy.DefineMethod("Main", _
                MethodAttributes.Public Or MethodAttributes.Static, _
                Nothing, Nothing)
        ilg = entryPoint.GetILGenerator()
        ' In order to call the static generic method GM, it is
        ' necessary to create a constructed type from the 
        ' generic type definition for Sample. This can be ANY
        ' constructed type; in this case Sample(Of Integer)
        ' is used.
        Dim SampleOfInt As Type = _
            myType.MakeGenericType(GetType(Integer))
        ' Next get a MethodInfo representing the static generic
        ' method GM on type Sample(Of Integer).
        Dim SampleOfIntGM As MethodInfo = _
            TypeBuilder.GetMethod(SampleOfInt, genMethod)
        ' Next get a MethodInfo for GM(Of String), which is the 
        ' instantiation of generic method GM that is called
        ' by Sub Main.
        Dim GMOfString As MethodInfo = _
            SampleOfIntGM.MakeGenericMethod(GetType(String))
        ' Finally, emit the call. Push a string onto
        ' the stack, as the argument for the generic method.
        ilg.Emit(OpCodes.Ldstr, "Hello, world!")
        ilg.EmitCall(OpCodes.Call, GMOfString, Nothing)
        ilg.Emit(OpCodes.Ret)
        
        myType.CreateType()
        dummy.CreateType()
        myAssembly.SetEntryPoint(entryPoint)
        myAssembly.Save(myAsmName.Name & ".exe")
        
        Console.WriteLine(myAsmName.Name & ".exe has been saved.")
    
    End Sub 
End Class 

注解

如果在定义方法时知道返回类型和参数的数目,则可以使用接受参数类型数组的 TypeBuilder.DefineMethod 方法的任何重载来建立它们。If the return type and the number and types of the parameters are known when the method is defined, they can be established using any overload of the TypeBuilder.DefineMethod method that accepts an array of parameter types. 但是,泛型方法可以具有其类型由一个或多个其自己的泛型类型参数指定的参数,在定义该方法之后,才能定义这些参数。However, a generic method can have parameters whose types are specified by one or more of its own generic type parameters, which cannot be defined until after the method has been defined. 在这种情况下,使用此方法设置参数类型。Use this method to set the parameter types in that case.

如果返回类型和参数类型都没有可选的或必需的自定义修饰符,如 IsConstModifier,则可以使用 SetReturnTypeSetParameters 方法。If neither the return type nor the parameter types have optional or required custom modifiers, such as IsConstModifier, you can use the SetReturnType and SetParameters methods.

调用此方法将替换使用 TypeBuilder.DefineMethod 方法建立的参数和返回类型。Calling this method replaces the parameters and return type established using the TypeBuilder.DefineMethod method.

适用于

另请参阅