Exportar (0) Imprimir
Expandir todo

MethodBuilder (Clase)

Actualización: noviembre 2007

Define y representa a un método (o constructor) de una clase dinámica.

Espacio de nombres:  System.Reflection.Emit
Ensamblado:  mscorlib (en mscorlib.dll)

[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class MethodBuilder : MethodInfo, 
	_MethodBuilder
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */
/** @attribute ComVisibleAttribute(true) */
/** @attribute HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true) */
public final class MethodBuilder extends MethodInfo implements _MethodBuilder
public final class MethodBuilder extends MethodInfo implements _MethodBuilder

3ssa260d.alert_note(es-es,VS.90).gifNota:

El atributo HostProtectionAttribute aplicado a este tipo o miembro tiene el siguiente valor de la propiedad Resources: MayLeakOnAbort. El atributo HostProtectionAttribute no afecta a las aplicaciones de escritorio (que normalmente se inician haciendo doble clic en un icono, escribiendo un comando o introduciendo una dirección URL en el explorador). Para obtener más información, vea la clase HostProtectionAttribute o Programación de SQL Server y atributos de protección del host.

MethodBuilder se utiliza para describir completamente un método en el Lenguaje intermedio de Microsoft (MSIL), incluido el nombre, los atributos, la firma y el cuerpo del método. Se utiliza junto con la clase TypeBuilder para crear clases en tiempo de ejecución.

A continuación, se incluye un ejemplo en el que se utiliza la clase MethodBuilder para crear un método en un tipo dinámico.


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

class DemoMethodBuilder 
{
    public static void AddMethodDynamically (TypeBuilder myTypeBld,
                                             string mthdName,
                                             Type[] mthdParams, 
                                             Type returnType,
                                             string mthdAction) 
    {

        MethodBuilder myMthdBld = myTypeBld.DefineMethod(
                                             mthdName,
                                             MethodAttributes.Public |
                                             MethodAttributes.Static,
                                             returnType,
                                             mthdParams);        

        ILGenerator ILout = myMthdBld.GetILGenerator();

        int numParams = mthdParams.Length;

        for (byte x=0; x < numParams; x++) 
        {
            ILout.Emit(OpCodes.Ldarg_S, x);
        }

        if (numParams > 1) 
        {
            for (int y=0; y<(numParams-1); y++) 
            {
                switch (mthdAction) 
                {
                    case "A": ILout.Emit(OpCodes.Add);
                              break;
                    case "M": ILout.Emit(OpCodes.Mul);
                              break;
                    default: ILout.Emit(OpCodes.Add);
                              break;
                }
            }
        }
        ILout.Emit(OpCodes.Ret);
    }

    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName asmName = new AssemblyName();
        asmName.Name = "MyDynamicAsm";

        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
                                       asmName, 
                                       AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule("MyDynamicAsm",
                                                                  "MyDynamicAsm.dll");

        TypeBuilder myTypeBld = myModule.DefineType("MyDynamicType",
                                                    TypeAttributes.Public);           

        // Get info from the user to build the method dynamically.
        Console.WriteLine("Let's build a simple method dynamically!");
        Console.WriteLine("Please enter a few numbers, separated by spaces.");
        string inputNums = Console.ReadLine();
        Console.Write("Do you want to [A]dd (default) or [M]ultiply these numbers? ");
        string myMthdAction = Console.ReadLine().ToUpper();
        Console.Write("Lastly, what do you want to name your new dynamic method? ");
        string myMthdName = Console.ReadLine();

        // Process inputNums into an array and create a corresponding Type array 
        int index = 0;
        string[] inputNumsList = inputNums.Split();

        Type[] myMthdParams = new Type[inputNumsList.Length];
        object[] inputValsList = new object[inputNumsList.Length];


        foreach (string inputNum in inputNumsList) 
        {
            inputValsList[index] = (object)Convert.ToInt32(inputNum);
                myMthdParams[index] = typeof(int);
                index++;
        } 

        // Now, call the method building method with the parameters, passing the 
        // TypeBuilder by reference.
        AddMethodDynamically(myTypeBld,
                             myMthdName,
                             myMthdParams,
                             typeof(int),        
                             myMthdAction);

        Type myType = myTypeBld.CreateType();

        Console.WriteLine("---");
        Console.WriteLine("The result of {0} the inputted values is: {1}",
                          ((myMthdAction == "M") ? "multiplying" : "adding"),
                          myType.InvokeMember(myMthdName,
                          BindingFlags.InvokeMethod | BindingFlags.Public |
                          BindingFlags.Static,
                          null,
                          null,
                          inputValsList));
        Console.WriteLine("---");

        // Let's take a look at the method we created.
        // If you are interested in seeing the MSIL generated dynamically for the method
        // your program generated, change to the directory where you ran the compiled
        // code sample and type "ildasm MyDynamicAsm.dll" at the prompt. When the list
        // of manifest contents appears, click on "MyDynamicType" and then on the name of
        // of the method you provided during execution.

        myAsmBuilder.Save("MyDynamicAsm.dll");

        MethodInfo myMthdInfo = myType.GetMethod(myMthdName);
        Console.WriteLine("Your Dynamic Method: {0};", myMthdInfo.ToString());    
    }
}


import System.*;
import System.Reflection.*;
import System.Reflection.Emit.*;

class DemoMethodBuilder
{
    public static void AddMethodDynamically(TypeBuilder myTypeBld,
        String mthdName, Type mthdParams[], Type returnType, String mthdAction)
    {
        MethodBuilder myMthdBld = myTypeBld.DefineMethod(mthdName,
            MethodAttributes.Public | MethodAttributes.Static,
            returnType, mthdParams);
        ILGenerator iLout = myMthdBld.GetILGenerator();
        int numParams = mthdParams.length;
        for (ubyte x = 0; x < numParams; x++) {
            iLout.Emit(OpCodes.Ldarg_S, x);
        }
        if (numParams > 1) {
            for (int y = 0; y < numParams - 1; y++) {
                if (mthdAction.Equals("A") == true) {
                    iLout.Emit(OpCodes.Add);
                }
                else if (mthdAction.Equals("M") == true) {
                    iLout.Emit(OpCodes.Mul);
                }
                else {
                    iLout.Emit(OpCodes.Add);
                }
            }
        }
        iLout.Emit(OpCodes.Ret);
    } //AddMethodDynamically

    public static void main(String[] args)
    {
        AppDomain myDomain = AppDomain.get_CurrentDomain();
        AssemblyName asmName = new AssemblyName();
        asmName.set_Name("MyDynamicAsm");
        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(asmName,
            AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule
            ("MyDynamicAsm", "MyDynamicAsm.dll");
        TypeBuilder myTypeBld = myModule.DefineType("MyDynamicType",
            TypeAttributes.Public);

        // Get info from the user to build the method dynamically.
        Console.WriteLine("Let's build a simple method dynamically!");
        Console.WriteLine("Please enter a few numbers, separated by spaces.");
        String inputNums = Console.ReadLine();
        Console.Write("Do you want to [A]dd (default) or [M]ultiply these numbers? ");
        String myMthdAction = Console.ReadLine().ToUpper();
        Console.Write("Lastly, what do you want to name your new "
            + "dynamic method? ");
        String myMthdName = Console.ReadLine();

        // Process inputNums into an array and create a corresponding
        // Type array 
        int index = 0;
        String inputNumsList[] = inputNums.Split(null);
        Type myMthdParams[] = new Type[inputNumsList.length];
        Object inputValsList[] = new Object[inputNumsList.length];
        for (int iCtr = 0; iCtr < inputNumsList.length; iCtr++) {
            String inputNum = inputNumsList[iCtr];
            inputValsList[index] = (Object)(Int32)Integer.parseInt(inputNum);
            myMthdParams.set_Item(index, int.class.ToType());
            index++;
        }

        // Now, call the method building method with the parameters,
        // passing the TypeBuilder by reference.
        AddMethodDynamically(myTypeBld, myMthdName, myMthdParams,
            int.class.ToType(), myMthdAction);
        Type myType = myTypeBld.CreateType();
        Console.WriteLine("---");
        Console.WriteLine("The result of {0} the inputted values is: {1}",
            (myMthdAction.equals("M")) ? "multiplying" : "adding",
            myType.InvokeMember(myMthdName, 
            BindingFlags.InvokeMethod | BindingFlags.Public |
            BindingFlags.Static, null, null, inputValsList));
        Console.WriteLine("---");

        // Let's take a look at the method we created.
        // If you are interested in seeing the MSIL generated dynamically for
        // the method your program generated, change to the directory where 
        // you ran the compiled code sample and type "ildasm MyDynamicAsm.dll"
        //  at the prompt. When the list of manifest contents appears, click on
        // "MyDynamicType" and then on the name of the method you provided 
        // during execution.

        myAsmBuilder.Save("MyDynamicAsm.dll");

        MethodInfo myMthdInfo = myType.GetMethod(myMthdName);
        Console.WriteLine("Your Dynamic Method: {0};", myMthdInfo.ToString());
    } 
} 


Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0

Adiciones de comunidad

AGREGAR
Mostrar:
© 2014 Microsoft