DynamicMethod 생성자
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
동적 메서드를 만듭니다.
오버로드
| Name | Description |
|---|---|
| DynamicMethod(String, Type, Type[]) |
메서드 이름, 반환 형식 및 매개 변수 형식을 지정하여 익명으로 호스트되는 동적 메서드를 초기화합니다. |
| DynamicMethod(String, Type, Type[], Boolean) |
메서드 이름, 반환 형식, 매개 변수 형식 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하여 익명으로 호스트되는 동적 메서드를 초기화합니다. |
| DynamicMethod(String, Type, Type[], Module) |
메서드 이름, 반환 형식, 매개 변수 형식 및 모듈을 지정하여 모듈에 전역적인 동적 메서드를 만듭니다. |
| DynamicMethod(String, Type, Type[], Type) |
메서드 이름, 반환 형식, 매개 변수 형식 및 동적 메서드가 논리적으로 연결된 형식을 지정하는 동적 메서드를 만듭니다. |
| DynamicMethod(String, Type, Type[], Module, Boolean) |
메서드 이름, 반환 형식, 매개 변수 형식, 모듈 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하여 모듈에 전역적인 동적 메서드를 만듭니다. |
| DynamicMethod(String, Type, Type[], Type, Boolean) |
메서드 이름, 반환 형식, 매개 변수 형식, 동적 메서드가 논리적으로 연결된 형식 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하는 동적 메서드를 만듭니다. |
| DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean) |
메서드 이름, 특성, 호출 규칙, 반환 형식, 매개 변수 형식, 모듈을 지정하고 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하여 모듈에 전역적인 동적 메서드를 만듭니다. |
| DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean) |
메서드 이름, 특성, 호출 규칙, 반환 형식, 매개 변수 형식, 동적 메서드가 논리적으로 연결된 형식 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하는 동적 메서드를 만듭니다. |
DynamicMethod(String, Type, Type[])
메서드 이름, 반환 형식 및 매개 변수 형식을 지정하여 익명으로 호스트되는 동적 메서드를 초기화합니다.
public:
DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type())
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
예외
is 또는 .의 parameterTypes 요소입니다null.Void
name은 null입니다.
.NET Framework 및 .NET Core 버전이 2.1보다 오래된 경우: returnType는 IsByReftrue 반환하는 형식입니다.
설명
이 생성자에서 만든 동적 메서드는 기존 형식 또는 모듈 대신 익명 어셈블리와 연결됩니다. 익명 어셈블리는 동적 메서드, 즉 다른 코드에서 격리하기 위한 샌드박스 환경을 제공하기 위해서만 존재합니다. 이 환경을 사용하면 동적 메서드를 부분적으로 신뢰할 수 있는 코드로 내보내고 실행할 수 있습니다.
이 생성자는 동적 메서드의 MSIL(Microsoft 중간 언어)에 대해 JIT(Just-In-Time) 표시 유형 검사가 적용되도록 지정합니다. 즉, 동적 메서드의 코드는 공용 클래스의 공용 메서드에 액세스할 수 있습니다. 메서드가 private, protected 또는 internal(Visual Basic Friend)인 형식이나 멤버에 액세스하려고 하면 예외가 throw됩니다. JIT 표시 유형 검사를 건너뛰는 기능이 제한된 동적 메서드를 만들려면 생성자를 사용합니다 DynamicMethod(String, Type, Type[], Boolean) .
익명으로 호스트되는 동적 메서드가 생성되면 내보내는 어셈블리의 호출 스택이 포함됩니다. 메서드가 호출될 때 내보내는 어셈블리의 사용 권한은 실제 호출자의 권한 대신 사용됩니다. 따라서 동적 메서드는 신뢰 수준이 높은 어셈블리에 전달되고 실행되는 경우에도 해당 메서드를 내보낸 어셈블리보다 높은 수준의 권한으로 실행할 수 없습니다.
이 생성자는 메서드 특성 MethodAttributes.Public 및 MethodAttributes.Static호출 규칙을 CallingConventions.Standard지정합니다.
메모
이 생성자는 .NET Framework 3.5 이상에서 도입되었습니다.
추가 정보
적용 대상
DynamicMethod(String, Type, Type[], Boolean)
메서드 이름, 반환 형식, 매개 변수 형식 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하여 익명으로 호스트되는 동적 메서드를 초기화합니다.
public:
DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, bool restrictedSkipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), restrictedSkipVisibility As Boolean)
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
- restrictedSkipVisibility
- Boolean
true동적 메서드의 MSIL에서 액세스하는 형식 및 멤버에 대한 JIT 표시 유형 검사를 건너뛰려면 이 제한을 사용합니다. 이러한 형식과 멤버를 포함하는 어셈블리의 신뢰 수준은 동적 메서드를 내보내는 호출 스택의 신뢰 수준과 같거나 같아야 합니다. 그렇지 않으면 . false
예외
is 또는 .의 parameterTypes 요소입니다null.Void
name은 null입니다.
.NET Framework 및 .NET Core 버전이 2.1보다 오래된 경우: returnType는 IsByReftrue 반환하는 형식입니다.
설명
이 생성자에서 만든 동적 메서드는 기존 형식 또는 모듈 대신 익명 어셈블리와 연결됩니다. 익명 어셈블리는 동적 메서드, 즉 다른 코드에서 격리하기 위한 샌드박스 환경을 제공하기 위해서만 존재합니다. 이 환경을 사용하면 동적 메서드를 부분적으로 신뢰할 수 있는 코드로 내보내고 실행할 수 있습니다.
익명으로 호스트되는 동적 메서드는 private, protected 또는 internal(Visual Basic Friend)인 형식이나 멤버에 자동으로 액세스할 수 없습니다. 이는 연결된 범위의 숨겨진 멤버에 액세스할 수 있는 기존 형식 또는 모듈과 연결된 동적 메서드와 다릅니다.
true 동적 메서드가 restrictedSkipVisibility, private, 또는 protected에 해당하는 형식이나 멤버에 액세스해야 하는 경우 internal을(를) 지정합니다. 이렇게 하면 동적 메서드가 이러한 멤버에 대한 액세스를 제한합니다. 즉, 다음 조건이 충족되는 경우에만 멤버에 액세스할 수 있습니다.
대상 멤버는 동적 메서드를 내보내는 호출 스택과 같거나 낮은 신뢰 수준이 있는 어셈블리에 속합니다.
동적 메서드를 내보내는 호출 스택은 플래그와 함께 ReflectionPermission 부여됩니다ReflectionPermissionFlag.RestrictedMemberAccess. 이는 코드가 완전 신뢰로 실행될 때 항상 해당됩니다. 부분적으로 신뢰할 수 있는 코드의 경우 호스트가 명시적으로 권한을 부여하는 경우에만 true입니다.
Important
권한이 부여되지 않은 경우 이 생성자를 호출할 때가 아니라 호출될 때 CreateDelegate 또는 동적 메서드가 호출될 때 보안 예외가 throw됩니다. 동적 메서드를 내보내는 데 특별한 권한이 필요하지 않습니다.
예를 들어 호출 스택에 제한된 멤버 액세스 권한이 부여된 경우 호출 스택에 있는 어셈블리의 프라이빗 멤버에 액세스할 수 있도록 설정된 true 동적 메서드가 있습니다restrictedSkipVisibility. 호출 스택에서 부분적으로 신뢰할 수 있는 코드를 사용하여 동적 메서드를 만든 경우 이러한 어셈블리가 완전히 신뢰할 수 있으므로 .NET Framework 어셈블리에서 형식의 프라이빗 멤버에 액세스할 수 없습니다.
restrictedSkipVisibility가 false인 경우, JIT 가시성 검사가 강제됩니다. 동적 메서드의 코드는 public 클래스의 public 메서드에 액세스할 수 있습니다. 그러나 형식 또는 멤버가 private, protected, internal인 경우에 액세스하려고 하면 예외가 throw됩니다.
익명으로 호스트되는 동적 메서드가 생성되면 내보내는 어셈블리의 호출 스택이 포함됩니다. 메서드가 호출될 때 내보내는 호출 스택의 사용 권한은 실제 호출자의 권한 대신 사용됩니다. 따라서 동적 메서드는 신뢰 수준이 높은 어셈블리에 전달되고 실행되는 경우에도 해당 메서드를 내보낸 어셈블리보다 높은 수준의 권한으로 실행할 수 없습니다.
이 생성자는 메서드 특성 MethodAttributes.Public 및 MethodAttributes.Static호출 규칙을 CallingConventions.Standard지정합니다.
메모
이 생성자는 .NET Framework 3.5 이상에서 도입되었습니다.
추가 정보
적용 대상
DynamicMethod(String, Type, Type[], Module)
메서드 이름, 반환 형식, 매개 변수 형식 및 모듈을 지정하여 모듈에 전역적인 동적 메서드를 만듭니다.
public:
DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), m As Module)
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
예외
.NET Framework 및 .NET Core 버전이 2.1보다 오래된 경우: returnType는 IsByReftrue 반환하는 형식입니다.
예제
다음 코드 예제에서는 두 개의 매개 변수를 사용하는 동적 메서드를 만듭니다. 이 예제에서는 첫 번째 매개 변수를 콘솔에 출력하는 간단한 함수 본문을 내보내고 두 번째 매개 변수를 메서드의 반환 값으로 사용합니다. 이 예제는 대리자를 생성하여 메서드를 완성한 후, 다른 매개변수로 대리자를 호출하고, 마지막으로 Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) 메서드를 사용하여 동적 메서드를 호출합니다.
using System;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.VisualBasic;
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 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 will cause an exception.
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 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 will cause 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
'
설명
이 생성자는 메서드 특성 MethodAttributes.Public 및 MethodAttributes.Static호출 규칙을 CallingConventions.Standard지정하고 JIT(Just-In-Time) 표시 유형 검사를 건너뛰지 않습니다.
이 생성자를 사용하여 만든 동적 메서드는 모듈internal에 포함된 모든 형식의 public 및 Friend (mVisual Basic에서) 멤버에 액세스할 수 있습니다.
메모
이전 버전과의 호환성을 위해, 이 생성자는 다음 두 가지 조건이 모두 만족될 때 SecurityPermission을(를) SecurityPermissionFlag.ControlEvidence 플래그와 함께 요구합니다: m가 호출 모듈이 아닌 다른 모듈일 때, 그리고 ReflectionPermission에 대해서 ReflectionPermissionFlag.MemberAccess 플래그가 실패한 경우입니다. 요청 SecurityPermission 이 성공하면 작업이 허용됩니다.
추가 정보
적용 대상
DynamicMethod(String, Type, Type[], Type)
메서드 이름, 반환 형식, 매개 변수 형식 및 동적 메서드가 논리적으로 연결된 형식을 지정하는 동적 메서드를 만듭니다.
public:
DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), owner As Type)
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
예외
is 또는 .의 parameterTypes 요소입니다null.Void
-또는-
owner 는 인터페이스, 배열, 열린 제네릭 형식 또는 제네릭 형식 또는 메서드의 형식 매개 변수입니다.
.NET Framework 및 .NET Core 버전이 2.1보다 오래된 경우: returnType는 IsByReftrue 반환하는 형식입니다.
예제
다음 코드 예제에서는 형식과 논리적으로 연결된 값을 만듭니다 DynamicMethod . 이 연결은 해당 형식의 프라이빗 멤버에 대한 액세스 권한을 부여합니다.
이 코드 예제는 프라이빗 필드를 가진 클래스 Example 을 정의하고, 첫 번째 클래스에서 파생된 클래스 DerivedFromExample, UseLikeStatic를 반환하고 Int32, Example 타입의 매개 변수를 갖는 형식의 대리자 Int32, UseLikeInstance를 반환하고 Int32 타입의 매개 변수를 갖는 형식의 대리자 Int32를 정의합니다.
그런 다음 예제 코드는 인스턴스 DynamicMethod 의 프라이빗 필드를 변경하고 이전 값을 반환하는 형식을 만듭니다Example.
메모
일반적으로 클래스의 내부 필드를 변경하는 것은 개체 지향 코딩 연습에 적합하지 않습니다.
예제 코드는 인스턴스 Example 를 만든 다음 두 대리자를 만듭니다. 첫 번째는 동적 메서드와 동일한 매개 변수를 포함하는 형식 UseLikeStatic입니다. 두 번째는 첫 번째 매개 변수(형식 UseLikeInstance)가 없는 형식 Example입니다. 이 대리자는 메서드 오버로드를 사용하여 CreateDelegate(Type, Object) 만들어집니다. 해당 메서드 오버로드의 두 번째 매개 변수는 인스턴스입니다 Example. 이 경우 방금 만든 인스턴스는 새로 만든 대리자에게 바인딩됩니다. 해당 대리자를 호출할 때마다 동적 메서드는 바인딩된 인스턴스 Example에서 작동합니다.
메모
이것은 .NET Framework 2.0에 도입된 대리자 바인딩의 완화된 규칙의 예이며, Delegate.CreateDelegate 메서드의 새로운 오버로드와 함께 제공됩니다. 자세한 내용은 Delegate 클래스를 참조하세요.
UseLikeStatic 대리자가 호출되어 해당 인스턴스 Example 가 대리자에게 UseLikeInstance 바인딩됩니다.
UseLikeInstance 그런 다음 두 대리자가 동일한 인스턴스Example에서 작동할 수 있도록 대리자가 호출됩니다. 내부 필드 값의 변경 내용은 각 호출 후에 표시됩니다. 마지막으로 대리자는 UseLikeInstance 인스턴스 DerivedFromExample에 바인딩되고 대리자 호출은 반복됩니다.
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'
설명
이 생성자로 만든 동적 메서드는 owner 형식의 모든 멤버와, internal을(를) 포함하는 모듈의 다른 모든 형식의 public 및 Friend (owner Visual Basic에서) 멤버에 접근할 수 있습니다.
이 생성자는 메서드 특성 MethodAttributes.Public 및 MethodAttributes.Static호출 규칙을 CallingConventions.Standard지정하고 JIT(Just-In-Time) 표시 유형 검사를 건너뛰지 않습니다.
메모
이전 버전과의 호환성을 위해, 이 생성자는 다음 두 조건이 모두 true일 때 SecurityPermission와 SecurityPermissionFlag.ControlEvidence 플래그를 요구합니다: owner가 호출 모듈이 아닌 다른 모듈에 있고, ReflectionPermission 플래그와 함께 ReflectionPermissionFlag.MemberAccess에 대한 요구가 실패한 경우. 요청 SecurityPermission 이 성공하면 작업이 허용됩니다.
추가 정보
적용 대상
DynamicMethod(String, Type, Type[], Module, Boolean)
메서드 이름, 반환 형식, 매개 변수 형식, 모듈 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하여 모듈에 전역적인 동적 메서드를 만듭니다.
public:
DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m, bool skipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), m As Module, skipVisibility As Boolean)
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
- skipVisibility
- Boolean
true 동적 메서드의 MSIL에서 액세스하는 형식 및 멤버에 대한 JIT 표시 유형 검사를 건너뜁니다.
예외
.NET Framework 및 .NET Core 버전이 2.1보다 오래된 경우: returnType는 IsByReftrue 반환하는 형식입니다.
설명
이 생성자는 메서드 특성 MethodAttributes.Public 및 MethodAttributes.Static호출 규칙을 CallingConventions.Standard지정합니다.
이 생성자를 사용하여 만든 동적 메서드는 포함된 모듈 m 모든 형식의 public 및 internal(Friend in Visual Basic) 멤버에 액세스할 수 있습니다. JIT 컴파일러의 표시 유형 검사를 건너뛰면 동적 메서드가 다른 모든 형식의 프라이빗 및 보호된 멤버에도 액세스할 수 있습니다. 예를 들어 개체를 직렬화하는 코드를 작성할 때 유용합니다.
메모
이전 버전과의 호환성을 위해, 이 생성자는 다음 두 가지 조건이 모두 만족될 때 SecurityPermission을(를) SecurityPermissionFlag.ControlEvidence 플래그와 함께 요구합니다: m가 호출 모듈이 아닌 다른 모듈일 때, 그리고 ReflectionPermission에 대해서 ReflectionPermissionFlag.MemberAccess 플래그가 실패한 경우입니다. 요청 SecurityPermission 이 성공하면 작업이 허용됩니다.
추가 정보
적용 대상
DynamicMethod(String, Type, Type[], Type, Boolean)
메서드 이름, 반환 형식, 매개 변수 형식, 동적 메서드가 논리적으로 연결된 형식 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하는 동적 메서드를 만듭니다.
public:
DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), owner As Type, skipVisibility As Boolean)
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
- skipVisibility
- Boolean
true동적 메서드의 MSIL에서 액세스하는 형식 및 멤버에 대한 JIT 표시 유형 검사를 건너뛰려면 그렇지 않으면 . false
예외
is 또는 .의 parameterTypes 요소입니다null.Void
-또는-
owner 는 인터페이스, 배열, 열린 제네릭 형식 또는 제네릭 형식 또는 메서드의 형식 매개 변수입니다.
.NET Framework 및 .NET Core 버전이 2.1보다 오래된 경우: returnType는 IsByReftrue 반환하는 형식입니다.
설명
이 생성자로 만든 동적 메서드는 owner 형식의 모든 멤버와, internal을(를) 포함하는 모듈의 다른 모든 형식의 public 및 Friend (owner Visual Basic에서) 멤버에 접근할 수 있습니다. JIT 컴파일러의 표시 유형 검사를 건너뛰면 동적 메서드가 다른 모든 형식의 프라이빗 및 보호된 멤버에도 액세스할 수 있습니다. 예를 들어 개체를 직렬화하는 코드를 작성할 때 유용합니다.
이 생성자는 메서드 특성 MethodAttributes.Public 및 MethodAttributes.Static호출 규칙을 CallingConventions.Standard지정합니다.
메모
이전 버전과의 호환성을 위해, 이 생성자는 다음 두 조건이 모두 true일 때 SecurityPermission와 SecurityPermissionFlag.ControlEvidence 플래그를 요구합니다: owner가 호출 모듈이 아닌 다른 모듈에 있고, ReflectionPermission 플래그와 함께 ReflectionPermissionFlag.MemberAccess에 대한 요구가 실패한 경우. 요청 SecurityPermission 이 성공하면 작업이 허용됩니다.
추가 정보
적용 대상
DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean)
메서드 이름, 특성, 호출 규칙, 반환 형식, 매개 변수 형식, 모듈을 지정하고 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하여 모듈에 전역적인 동적 메서드를 만듭니다.
public:
DynamicMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m, bool skipVisibility);
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), m As Module, skipVisibility As Boolean)
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
- attributes
- MethodAttributes
동적 메서드의 MethodAttributes 특성을 지정하는 값의 비트 조합입니다. 허용되는 유일한 조합은 Public and Static.
- callingConvention
- CallingConventions
동적 메서드에 대한 호출 규칙입니다. Standard이어야 합니다.
- skipVisibility
- Boolean
true동적 메서드의 MSIL에서 액세스하는 형식 및 멤버에 대한 JIT 표시 유형 검사를 건너뛰려면 그렇지 않으면 . false
예외
attributes 은 (와) 이외의 Public 플래그 조합입니다 Static.
-또는-
callingConvention 가 아닙니다 Standard.
-또는-
returnType은 .를 반환true하는 형식입니다IsByRef.
설명
이 생성자를 사용하여 만든 동적 메서드는 모듈 m 포함된 모든 public 및 내부 형식의 public 및 internal(Friend Visual Basic) 멤버에 액세스할 수 있습니다.
JIT 컴파일러의 표시 유형 검사를 건너뛰면 동적 메서드가 모듈 및 다른 모든 어셈블리의 다른 모든 형식의 프라이빗 및 보호된 멤버에 액세스할 수 있습니다. 예를 들어 개체를 직렬화하는 코드를 작성할 때 유용합니다.
메모
이전 버전과의 호환성을 위해, 이 생성자는 다음 두 가지 조건이 모두 만족될 때 SecurityPermission을(를) SecurityPermissionFlag.ControlEvidence 플래그와 함께 요구합니다: m가 호출 모듈이 아닌 다른 모듈일 때, 그리고 ReflectionPermission에 대해서 ReflectionPermissionFlag.MemberAccess 플래그가 실패한 경우입니다. 요청 SecurityPermission 이 성공하면 작업이 허용됩니다.
추가 정보
적용 대상
DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean)
메서드 이름, 특성, 호출 규칙, 반환 형식, 매개 변수 형식, 동적 메서드가 논리적으로 연결된 형식 및 동적 메서드의 MSIL(Microsoft 중간 언어)에서 액세스하는 형식 및 멤버에 대해 JIT(Just-In-Time) 표시 여부를 지정하는 동적 메서드를 만듭니다.
public:
DynamicMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), owner As Type, skipVisibility As Boolean)
매개 변수
- name
- String
동적 메서드의 이름입니다. 길이가 0인 문자열일 수 있지만 0일 수는 없습니다 null.
- attributes
- MethodAttributes
동적 메서드의 MethodAttributes 특성을 지정하는 값의 비트 조합입니다. 허용되는 유일한 조합은 Public and Static.
- callingConvention
- CallingConventions
동적 메서드에 대한 호출 규칙입니다. Standard이어야 합니다.
- skipVisibility
- Boolean
true동적 메서드의 MSIL에서 액세스하는 형식 및 멤버에 대한 JIT 표시 유형 검사를 건너뛰려면 그렇지 않으면 . false
예외
is 또는 .의 parameterTypes 요소입니다null.Void
-또는-
owner 는 인터페이스, 배열, 열린 제네릭 형식 또는 제네릭 형식 또는 메서드의 형식 매개 변수입니다.
attributes 은 (와) 이외의 Public 플래그 조합입니다 Static.
-또는-
callingConvention 가 아닙니다 Standard.
-또는-
returnType은 .를 반환true하는 형식입니다IsByRef.
설명
동적 메서드는 형식 owner이 포함된 모듈에 전역입니다. 형식의 모든 멤버에 액세스할 수 있습니다 owner.
이 생성자를 사용하여 만든 동적 메서드는 owner 형식의 모든 멤버와 owner 포함하는 모듈에 포함된 모든 형식의 public 및 internal(Visual Basic에서는 Friend) 멤버에 액세스할 수 있습니다. JIT 컴파일러의 표시 유형 검사를 건너뛰면 동적 메서드가 다른 모든 형식의 프라이빗 및 보호된 멤버에도 액세스할 수 있습니다. 예를 들어 개체를 직렬화하는 코드를 작성할 때 유용합니다.
메모
이전 버전과의 호환성을 위해, 이 생성자는 다음 두 조건이 모두 true일 때 SecurityPermission와 SecurityPermissionFlag.ControlEvidence 플래그를 요구합니다: owner가 호출 모듈이 아닌 다른 모듈에 있고, ReflectionPermission 플래그와 함께 ReflectionPermissionFlag.MemberAccess에 대한 요구가 실패한 경우. 요청 SecurityPermission 이 성공하면 작업이 허용됩니다.