Dieser Artikel wurde noch nicht bewertet - Dieses Thema bewerten.

MethodBuilder-Klasse

Definiert eine Methode (oder einen Konstruktor) in einer dynamischen Klasse und stellt diese bzw. diesen dar.

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

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

Das auf diese Klasse angewendete HostProtectionAttribute-Attribut besitzt den Resources-Eigenschaftenwert MayLeakOnAbort. Das HostProtectionAttribute hat keine Auswirkungen auf Desktopanwendungen (die normalerweise durch Doppelklicken auf ein Symbol, Eingeben eines Befehls oder eines URL in einem Browser gestartet werden). Weitere Informationen finden Sie unter der HostProtectionAttribute-Klasse oder unter SQL Server-Programmierung und Hostschutzattribute.

MethodBuilder wird verwendet, um eine Methode vollständig in Microsoft Intermediate Language (MSIL) zu beschreiben (einschließlich Name, Attribute, Signatur und Methodenkörper). Er wird zusammen mit der TypeBuilder-Klasse verwendet, um Klassen zur Laufzeit zu erstellen.

Ein Beispiel, in dem die MethodBuilder-Klasse zum Erstellen einer Methode innerhalb eines dynamischen Typs verwendet wird, finden Sie weiter unten.


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


class DemoMethodBuilder {

	public static void AddMethodDynamically (ref 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 = Thread.GetDomain();
	   AssemblyName asmName = new AssemblyName();
	   asmName.Name = "DynamicAssembly1";
	
	   AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
					  asmName, 
					  AssemblyBuilderAccess.RunAndSave);

   	   ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule("DynamicModule1",
							   	     "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 or [M]ultiply these numbers? ");
	   string myMthdAction = Console.ReadLine();
	   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(ref myTypeBld,
				myMthdName,
				myMthdParams,
				typeof(int),	
				myMthdAction);

	   Type myType = myTypeBld.CreateType();

	   Console.WriteLine("---");
	   Console.WriteLine("The result of {0} the inputted values is: {1}",
			     ((myMthdAction == "A") ? "adding" : "multiplying"),
			     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.Threading.*;
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 = System.Threading.Thread.GetDomain();
        AssemblyName asmName = new AssemblyName();
        asmName.set_Name("DynamicAssembly1");
        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(asmName,
            AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule
            ("DynamicModule1", "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 or [M]ultiply these numbers? ");
        String myMthdAction = Console.ReadLine();
        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("A")) ? "adding" : "multiplying",
            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());
    } //main 
} //DemoMethodBuilder

System.Object
   System.Reflection.MemberInfo
     System.Reflection.MethodBase
       System.Reflection.MethodInfo
        System.Reflection.Emit.MethodBuilder
Alle öffentlichen statischen (Shared in Visual Basic) Member dieses Typs sind threadsicher. Bei Instanzmembern ist die Threadsicherheit nicht gewährleistet.

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

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0
Fanden Sie dies hilfreich?
(1500 verbleibende Zeichen)
© 2013 Microsoft. Alle Rechte vorbehalten.