System.Reflection.Emit.DynamicMethod-constructors

Opmerking

In dit artikel vindt u aanvullende opmerkingen in de referentiedocumentatie voor deze API.

DynamicMethod(String, Type, Type[], Boolean) bouwer

De dynamische methode die door deze constructor wordt gemaakt, is gekoppeld aan een anonieme assembly in plaats van een bestaand type of een bestaande module. De anonieme assembly bestaat alleen om een sandbox-omgeving te bieden voor dynamische methoden, dat wil gezegd, om ze te isoleren van andere code. Deze omgeving maakt het veilig voor de dynamische methode die wordt verzonden en uitgevoerd door gedeeltelijk vertrouwde code.

Anonieme, gehoste dynamische methoden hebben geen automatische toegang tot alle typen of leden die , privateprotectedof internal (Friend in Visual Basic) zijn. Dit verschilt van dynamische methoden die zijn gekoppeld aan een bestaand type of een bestaande module, die toegang hebben tot verborgen leden in het bijbehorende bereik.

Specificeer true voor restrictedSkipVisibility als uw dynamische methode toegang moet hebben tot typen of leden die private, protected, of internal zijn. Dit biedt de dynamische methode beperkte toegang tot deze leden. Dat wil zeggen: de leden kunnen alleen toegankelijk zijn als aan de volgende voorwaarden wordt voldaan.

  • De doelgroepen behoren tot een assemblage met een vertrouwensniveau dat gelijk is aan of lager is dan de aanroepstapel die de dynamische methode uitvoert.

  • De aanroepstack die de dynamische methode produceert, krijgt ReflectionPermission met de ReflectionPermissionFlag.RestrictedMemberAccess vlag. Dit geldt altijd wanneer de code wordt uitgevoerd met volledig vertrouwen. Voor gedeeltelijk vertrouwde code geldt dit alleen als de host expliciet de machtiging verleent.

    Belangrijk

    Als de machtiging niet is verleend, wordt er een beveiligingsonderzondering gegenereerd wanneer CreateDelegate deze wordt aangeroepen of wanneer de dynamische methode wordt aangeroepen, niet wanneer deze constructor wordt aangeroepen. Er zijn geen speciale machtigingen vereist om de dynamische methode te verzenden.

Bijvoorbeeld, een dynamische methode die is gemaakt met restrictedSkipVisibility ingesteld op true kan toegang krijgen tot een privélid van een assembly op de oproepstack, als aan de oproepstack beperkte lidtoegang is verleend. Als de dynamische methode wordt gemaakt met gedeeltelijk vertrouwde code op de call stack, kan deze geen toegang krijgen tot een privélid van een type in een .NET Framework-assembly, omdat dergelijke assemblies volledig vertrouwd zijn.

Als restrictedSkipVisibilityfalse is, worden JIT-zichtbaarheidscontroles afgedwongen. De code in de dynamische methode heeft toegang tot openbare methoden van openbare klassen en uitzonderingen worden opgegooid als wordt geprobeerd toegang te verkrijgen tot typen of leden die private, protected of internal.

Wanneer een anoniem gehoste dynamische methode wordt samengesteld, wordt de aanroepstack van de verzendende assembly opgenomen. Wanneer de methode wordt aangeroepen, worden de machtigingen van de aanroepstack voor het verzenden van aanroepen gebruikt in plaats van de machtigingen van de werkelijke aanroeper. De dynamische methode kan dus niet worden uitgevoerd op een hoger niveau van bevoegdheden dan die van de assembly die deze heeft verzonden, zelfs niet als deze wordt doorgegeven aan en uitgevoerd door een assembly met een hoger vertrouwensniveau.

Met deze constructor worden de methodekenmerken MethodAttributes.Public en MethodAttributes.Static, en de aanroepende conventie CallingConventions.Standardopgegeven.

Opmerking

Deze constructor is geïntroduceerd in .NET Framework 3.5 of hoger.

DynamicMethod(String, Type, Type[], Module) bouwer

Met deze constructor worden methodekenmerken MethodAttributes.Public, de aanroepconventie MethodAttributes.Static, en JIT-zichtbaarheidscontroles CallingConventions.Standard (Just-In-Time) niet overgeslagen.

De dynamische methode die met deze constructor is gemaakt, heeft toegang tot publieke en internal (Friend in Visual Basic) leden van alle typen die in de module m zijn opgenomen.

Opmerking

Voor compatibiliteit met eerdere versies vereist deze constructor SecurityPermission met de SecurityPermissionFlag.ControlEvidence vlag als aan de volgende voorwaarden is voldaan: m is een andere module dan de aanroepende module, en de eis voor ReflectionPermission met de ReflectionPermissionFlag.MemberAccess vlag is mislukt. Als de vraag naar SecurityPermission slaagt, is de bewerking toegestaan.

Voorbeelden

In het volgende codevoorbeeld wordt een dynamische methode gemaakt die twee parameters gebruikt. In het voorbeeld wordt een eenvoudige functietekst verzonden waarmee de eerste parameter naar de console wordt afgedrukt. In het voorbeeld wordt de tweede parameter gebruikt als de retourwaarde van de methode. In het voorbeeld wordt de methode voltooid door een gemachtigde te maken, de gemachtigde aan te roepen met verschillende parameters en ten slotte de dynamische methode aan te roepen met behulp van de Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) methode.

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

public class Test
{
    // Declare a delegate that will be used to execute the completed
    // dynamic method.
    private delegate int HelloInvoker(string msg, int ret);

    public static void Main()
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This method has a string parameter
        // and an int parameter.
        Type[] helloArgs = {typeof(string), typeof(int)};

        // Create a dynamic method with the name "Hello", a return type
        // of int, and two parameters whose types are specified by the
        // array helloArgs. Create the method in the module that
        // defines the Test class.
        DynamicMethod hello = new DynamicMethod("Hello",
            typeof(int),
            helloArgs,
            typeof(Test).Module);

        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type[] writeStringArgs = {typeof(string)};
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString =
            typeof(Console).GetMethod("WriteLine", writeStringArgs);

        // Get an ILGenerator and emit a body for the dynamic method.
        ILGenerator il = hello.GetILGenerator();
        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the second argument onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ret);

        // Create a delegate that represents the dynamic method. This
        // action completes the method. Further attempts to change the
        // method are ignored and no exception is thrown.
        HelloInvoker hi =
            (HelloInvoker) hello.CreateDelegate(typeof(HelloInvoker));

        // Use the delegate to execute the dynamic method. Save and
        // print the return value.
        int retval = hi("\r\nHello, World!", 42);
        Console.WriteLine("Executing delegate hi(\"Hello, World!\", 42) returned {0}",
            retval);

        // Do it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Executing delegate hi(\"Hi, Mom!\", 5280) returned {0}",
            retval);

        // Create an array of arguments to use with the Invoke method.
        object[] invokeArgs = {"\r\nHello, World!", 42};
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and ValueType arguments
        // must be boxed.
        object objRet = hello.Invoke(null, invokeArgs);
        Console.WriteLine("hello.Invoke returned {0}", objRet);
    }
}
Imports System.Reflection
Imports System.Reflection.Emit

Public Class Test
    ' Declare a delegate that will be used to execute the completed
    ' dynamic method. 
    Private Delegate Function HelloInvoker(ByVal msg As String, _
        ByVal ret As Integer) As Integer

    Public Shared Sub Main()
        ' Create an array that specifies the types of the parameters
        ' of the dynamic method. This method has a String parameter
        ' and an Integer parameter.
        Dim helloArgs() As Type = {GetType(String), GetType(Integer)}

        ' Create a dynamic method with the name "Hello", a return type
        ' of Integer, and two parameters whose types are specified by
        ' the array helloArgs. Create the method in the module that
        ' defines the Test class.
        Dim hello As New DynamicMethod("Hello", _
            GetType(Integer), _
            helloArgs, _
            GetType(Test).Module)

        ' Create an array that specifies the parameter types of the
        ' overload of Console.WriteLine to be used in Hello.
        Dim writeStringArgs() As Type = {GetType(String)}
        ' Get the overload of Console.WriteLine that has one
        ' String parameter.
        Dim writeString As MethodInfo = GetType(Console). _
            GetMethod("WriteLine", writeStringArgs) 

        ' Get an ILGenerator and emit a body for the dynamic method.
        Dim il As ILGenerator = hello.GetILGenerator()
        ' Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0)
        ' Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, Nothing)
        ' The Hello method returns the value of the second argument;
        ' to do this, load the second argument onto the stack and return.
        il.Emit(OpCodes.Ldarg_1)
        il.Emit(OpCodes.Ret)

        ' Create a delegate that represents the dynamic method. This
        ' action completes the method, and any further attempts to
        ' change the method are ignored and don't throw an exception.
    Dim hi As HelloInvoker = _
            hello.CreateDelegate(GetType(HelloInvoker))

        ' Use the delegate to execute the dynamic method. Save and
        ' print the return value.
        Dim retval As Integer = hi(vbCrLf & "Hello, World!", 42)
        Console.WriteLine("Executing delegate hi(""Hello, World!"", 42) returned " _
            & retval)

        ' Do it again, with different arguments.
        retval = hi(vbCrLf & "Hi, Mom!", 5280)
        Console.WriteLine("Executing delegate hi(""Hi, Mom!"", 5280) returned " _
            & retval)

        ' Create an array of arguments to use with the Invoke method.
        Dim invokeArgs() As Object = {vbCrLf & "Hello, World!", 42}
        ' Invoke the dynamic method using the arguments. This is much
        ' slower than using the delegate, because you must create an
        ' array to contain the arguments, and ValueType arguments
        ' must be boxed. Note that this overload of Invoke is 
        ' inherited from MethodBase, and simply calls the more 
        ' complete overload of Invoke.
        Dim objRet As Object = hello.Invoke(Nothing, invokeArgs)
        Console.WriteLine("hello.Invoke returned " & objRet)
    End Sub
End Class

' This code example produces the following output:
'
'Hello, World!
'Executing delegate hi("Hello, World!", 42) returned 42
'
'Hi, Mom!
'Executing delegate hi("Hi, Mom!", 5280) returned 5280
'
'Hello, World!
'hello.Invoke returned 42
'

DynamicMethod(String, Type, Type[], Type) bouwer

De dynamische methode die met deze constructor is gemaakt, heeft toegang tot alle leden van het type owner en tot openbare en internal (Friend in Visual Basic) leden van alle andere typen in de module die owner bevat.

Met deze constructor worden methodekenmerken MethodAttributes.Public, de aanroepconventie MethodAttributes.Static, en JIT-zichtbaarheidscontroles CallingConventions.Standard (Just-In-Time) niet overgeslagen.

Opmerking

Voor compatibiliteit met eerdere versies vereist deze constructor gebruik van SecurityPermission met de SecurityPermissionFlag.ControlEvidence vlag als aan de volgende voorwaarden is voldaan: owner bevindt zich in een andere module dan de aanroepende module en de eis dat ReflectionPermission met de ReflectionPermissionFlag.MemberAccess vlag is mislukt. Als de vraag naar SecurityPermission slaagt, is de bewerking toegestaan.

Voorbeelden

In het volgende codevoorbeeld wordt een DynamicMethod logisch gekoppeld aan een type gemaakt. Deze associatie geeft het toegang tot de privéleden van dat type.

In het codevoorbeeld wordt een klasse gedefinieerd die is benoemd Example met een privéveld, een klasse DerivedFromExample die is afgeleid van de eerste klasse, een gemachtigdentype dat UseLikeStatic wordt geretourneerd Int32 en parameters van het type Example retourneert en Int32een gemachtigdentype dat UseLikeInstance retourneert Int32 en één parameter van het type Int32heeft.

De voorbeeldcode creëert een DynamicMethod die het privéveld van een instantie van Example verandert en de vorige waarde teruggeeft.

Opmerking

Over het algemeen is het wijzigen van de interne velden van klassen geen goede objectgeoriënteerde coderingspraktijk.

De voorbeeldcode maakt een exemplaar van Example en maakt vervolgens twee gemachtigden. De eerste is van het type UseLikeStatic, dat dezelfde parameters heeft als de dynamische methode. De tweede is van het type UseLikeInstance, dat de eerste parameter (van het type Example) ontbreekt. Deze delegate wordt gemaakt met behulp van de CreateDelegate(Type, Object) methodeoverload; de tweede parameter van die methodeoverload is een exemplaar van Example, in dit geval het exemplaar dat zojuist is gemaakt, dat gebonden is aan de nieuw gemaakte delegate. Wanneer die gemachtigde wordt aangeroepen, handelt de dynamische methode op het afhankelijke exemplaar van Example.

Opmerking

Dit is een voorbeeld van de versoepelde regels voor gedelegeerde binding die zijn geïntroduceerd in .NET Framework 2.0, samen met nieuwe overbelastingen van de Delegate.CreateDelegate methode. Zie de Delegate klas voor meer informatie.

De UseLikeStatic delegate wordt aangeroepen, en het wordt doorgegeven aan de instantie van Example dat is gebonden aan de UseLikeInstance delegate. Vervolgens wordt de UseLikeInstance gedelegeerde aangeroepen, zodat beide gedelegeerden op dezelfde instantie van Example werken. De wijzigingen in de waarden van het interne veld worden na elke aanroep weergegeven. Ten slotte is een UseLikeInstance delegate gebonden aan een instantie van DerivedFromExample, en worden de delegate-oproepen herhaald.

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

// These classes are for demonstration purposes.
//
public class Example
{
    private int id = 0;
    public Example(int id)
    {
        this.id = id;
    }
    public int ID { get { return id; }}
}

public class DerivedFromExample : Example
{
    public DerivedFromExample(int id) : base(id) {}
}

// Two delegates are declared: UseLikeInstance treats the dynamic
// method as if it were an instance method, and UseLikeStatic
// treats the dynamic method in the ordinary fashion.
//
public delegate int UseLikeInstance(int newID);
public delegate int UseLikeStatic(Example ex, int newID);

public class Demo
{
    public static void Main()
    {
        // This dynamic method changes the private id field. It has
        // no name; it returns the old id value (return type int);
        // it takes two parameters, an instance of Example and
        // an int that is the new value of id; and it is declared
        // with Example as the owner type, so it can access all
        // members, public and private.
        //
        DynamicMethod changeID = new DynamicMethod(
            "",
            typeof(int),
            new Type[] { typeof(Example), typeof(int) },
            typeof(Example)
        );

        // Get a FieldInfo for the private field 'id'.
        FieldInfo fid = typeof(Example).GetField(
            "id",
            BindingFlags.NonPublic | BindingFlags.Instance
        );

        ILGenerator ilg = changeID.GetILGenerator();

        // Push the current value of the id field onto the
        // evaluation stack. It's an instance field, so load the
        // instance of Example before accessing the field.
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldfld, fid);

        // Load the instance of Example again, load the new value
        // of id, and store the new field value.
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldarg_1);
        ilg.Emit(OpCodes.Stfld, fid);

        // The original value of the id field is now the only
        // thing on the stack, so return from the call.
        ilg.Emit(OpCodes.Ret);

        // Create a delegate that uses changeID in the ordinary
        // way, as a static method that takes an instance of
        // Example and an int.
        //
        UseLikeStatic uls =
            (UseLikeStatic) changeID.CreateDelegate(
                typeof(UseLikeStatic)
            );

        // Create an instance of Example with an id of 42.
        //
        Example ex = new Example(42);

        // Create a delegate that is bound to the instance of
        // of Example. This is possible because the first
        // parameter of changeID is of type Example. The
        // delegate has all the parameters of changeID except
        // the first.
        UseLikeInstance uli =
            (UseLikeInstance) changeID.CreateDelegate(
                typeof(UseLikeInstance),
                ex
            );

        // First, change the value of id by calling changeID as
        // a static method, passing in the instance of Example.
        //
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uls(ex, 1492)
        );

        // Change the value of id again using the delegate bound
        // to the instance of Example.
        //
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uli(2700)
        );

        Console.WriteLine("Final value of id: {0}", ex.ID);

        // Now repeat the process with a class that derives
        // from Example.
        //
        DerivedFromExample dfex = new DerivedFromExample(71);

        uli = (UseLikeInstance) changeID.CreateDelegate(
                typeof(UseLikeInstance),
                dfex
            );

        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uls(dfex, 73)
        );
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uli(79)
        );
        Console.WriteLine("Final value of id: {0}", dfex.ID);
    }
}

/* This code example produces the following output:

Change the value of id; previous value: 42
Change the value of id; previous value: 1492
Final value of id: 2700
Change the value of id; previous value: 71
Change the value of id; previous value: 73
Final value of id: 79
 */
Imports System.Reflection
Imports System.Reflection.Emit

' These classes are for demonstration purposes.
'
Public Class Example
    Private _id As Integer = 0
    
    Public Sub New(ByVal newId As Integer) 
        _id = newId    
    End Sub
    
    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property 
End Class

Public Class DerivedFromExample
    Inherits Example
    
    Public Sub New(ByVal newId As Integer) 
        MyBase.New(newId)
    End Sub
End Class
 
' Two delegates are declared: UseLikeInstance treats the dynamic
' method as if it were an instance method, and UseLikeStatic
' treats the dynamic method in the ordinary fashion.
' 
Public Delegate Function UseLikeInstance(ByVal newID As Integer) _
    As Integer 
Public Delegate Function UseLikeStatic(ByVal ex As Example, _
    ByVal newID As Integer) As Integer 

Public Class Demo
    
    Public Shared Sub Main() 
        ' This dynamic method changes the private _id field. It 
        ' has no name; it returns the old _id value (return type 
        ' Integer); it takes two parameters, an instance of Example 
        ' and an Integer that is the new value of _id; and it is 
        ' declared with Example as the owner type, so it can 
        ' access all members, public and private.
        '
        Dim changeID As New DynamicMethod( _
            "", _
            GetType(Integer), _
            New Type() {GetType(Example), GetType(Integer)}, _
            GetType(Example) _
        )
        
        ' Get a FieldInfo for the private field '_id'.
        Dim fid As FieldInfo = GetType(Example).GetField( _
            "_id", _
            BindingFlags.NonPublic Or BindingFlags.Instance _
        )
        
        Dim ilg As ILGenerator = changeID.GetILGenerator()
        
        ' Push the current value of the id field onto the 
        ' evaluation stack. It's an instance field, so load the
        ' instance of Example before accessing the field.
        ilg.Emit(OpCodes.Ldarg_0)
        ilg.Emit(OpCodes.Ldfld, fid)
        
        ' Load the instance of Example again, load the new value 
        ' of id, and store the new field value. 
        ilg.Emit(OpCodes.Ldarg_0)
        ilg.Emit(OpCodes.Ldarg_1)
        ilg.Emit(OpCodes.Stfld, fid)
        
        ' The original value of the id field is now the only 
        ' thing on the stack, so return from the call.
        ilg.Emit(OpCodes.Ret)
        
        
        ' Create a delegate that uses changeID in the ordinary
        ' way, as a static method that takes an instance of
        ' Example and an Integer.
        '
        Dim uls As UseLikeStatic = CType( _
            changeID.CreateDelegate(GetType(UseLikeStatic)), _
            UseLikeStatic _
        )
        
        ' Create an instance of Example with an id of 42.
        '
        Dim ex As New Example(42)
        
        ' Create a delegate that is bound to the instance of 
        ' of Example. This is possible because the first 
        ' parameter of changeID is of type Example. The 
        ' delegate has all the parameters of changeID except
        ' the first.
        Dim uli As UseLikeInstance = CType( _
            changeID.CreateDelegate( _
                GetType(UseLikeInstance), _
                ex), _
            UseLikeInstance _
        )
        
        ' First, change the value of _id by calling changeID as
        ' a static method, passing in the instance of Example.
        '
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uls(ex, 1492) _
        )
        
        ' Change the value of _id again using the delegate 
        ' bound to the instance of Example.
        '
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uli(2700) _
        )
        
        Console.WriteLine("Final value of _id: {0}", ex.ID)
    

        ' Now repeat the process with a class that derives
        ' from Example.
        '
        Dim dfex As New DerivedFromExample(71)

        uli = CType( _
            changeID.CreateDelegate( _
                GetType(UseLikeInstance), _
                dfex), _
            UseLikeInstance _
        )

        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uls(dfex, 73) _
        )
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uli(79) _
        )
        Console.WriteLine("Final value of _id: {0}", dfex.ID)

    End Sub
End Class

' This code example produces the following output:
'
'Change the value of _id; previous value: 42
'Change the value of _id; previous value: 1492
'Final value of _id: 2700
'Change the value of _id; previous value: 71
'Change the value of _id; previous value: 73
'Final value of _id: 79'