TypeBuilder.GetMethod(Type, MethodInfo) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
回傳對應於該定義中指定方法的指定構造通用型別的方法。
public:
static System::Reflection::MethodInfo ^ GetMethod(Type ^ type, System::Reflection::MethodInfo ^ method);
public static System.Reflection.MethodInfo GetMethod(Type type, System.Reflection.MethodInfo method);
static member GetMethod : Type * System.Reflection.MethodInfo -> System.Reflection.MethodInfo
Public Shared Function GetMethod (type As Type, method As MethodInfo) As MethodInfo
參數
- type
- Type
返回方法的構造型別。
- method
- MethodInfo
一個基於一般 type型別定義的方法,該定義指定要回傳的 type 哪種方法。
傳回
一個 MethodInfo 代表 的方法 type 的物件,對應 method於 ,該物件指定了屬於一般 type型別定義 的方法。
例外狀況
method 是一個非通用方法定義的通用方法。
-或-
type 不代表一般類型。
-或-
type 不屬於 TypeBuilder類型。
-或-
宣告型 method 別並非泛型定義。
-或-
宣告型 method 別並非的 type一般型別定義。
範例
以下程式碼範例包含一個名為 Sample 的通用類別的原始碼,該類別的型別參數名為 T。 該類別有一個名為 Field的欄位,型別 T為 ,以及一個帶有自身型別參數的通用方法 GM ,稱為 U。 方法 GM 建立一個 的 Sample實例,將自己的型別參數 U 替換為 的型別參數 Sample,並將輸入參數存於 Field。 這些原始碼會被編譯但不會使用;你可以用 Ildasm.exe(IL 反組譯器) 查看,並與類別 Example所發出的程式碼比較。
課堂 Example 上的程式碼示範了如何使用此 GetMethod 方法來發出通用程式碼。
Main類別Example的方法會建立一個動態組合,包含一個名為 Sample 的類別,並利用該DefineGenericParameters方法加入名為 T的型別參數來使其成為通用的類別。 一個無參數建構子與一個名為 Field的欄位,類型為 T,會被加入類別 Sample。 透過使用MethodBuilder.DefineGenericParameters該方法,將一個方法GM加入並轉化為通用方法。 的 GM 型態參數命名 U為 。 定義型別參數後,使用該方法加入 MethodBuilder.SetSignature 的GM簽名。 此方法沒有回傳類型,也沒有必要或自訂的修飾符,因此此方法的所有參數除了nullparameterTypes;parameterTypes將該方法唯一參數的類型設為 U,也就是該方法的通用類型參數。 方法主體會建立建構型別 Sample<U>(Visual Basic 中為 Sample(Of U)),將方法參數指派給 Field,然後印出 Field。 定義了一個虛擬型別來保存入口點方法 Main。 在 Main 的主體中,靜態 GM 方法被調用在構造的一般型 Sample<int>(Visual Basic 中稱為 Sample(Of Integer)),並將型別 String 取代 U。 該GetMethod方法用於為構造的泛型的Sample<U>靜態GM方法建立 ,MethodInfo接著MethodInfo.MakeGenericMethod該方法用於建立MethodInfo可在方法呼叫中發出的 。
執行程式碼範例時,會將所發出的組合語言儲存為 TypeBuilderGetFieldExample.exe。 你可以執行 TypeBuilderGetFieldExample.exe,並使用 Ildasm.exe(IL 反組譯器) 將所發出的程式碼與 Sample 編譯成程式碼範例的類別程式碼進行比較。
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
備註
此 GetMethod 方法提供一種方法,讓物件 MethodInfo 代表一個構造化的泛型方法,該方法的泛型定義由物件 TypeBuilder 表示。
舉例來說,假設你有一個 TypeBuilder 物件,代表 C# 語法中的 G<T>(Visual Basic 中的 G(Of T)),以及一個 MethodBuilder 物件,代表一個 C# 語法中的方法 T M()(Visual Basic 中的 Function M() As T),由 G<T> 定義。 假設 G<T> 有一個帶有型別參數 U 的通用方法,該方法建立該建構型別 G<U> 的實例,並呼叫 M 該實例的方法。 為了發出函式呼叫,你需要一個 MethodInfo 在建構型別上表示 M 的物件——換句話說,回傳型別 U 而非型別 T。 為此,首先呼叫MakeGenericType物件上TypeBuilder的方法,指定代表U型別參數的物件。GenericTypeParameterBuilder 接著呼叫GetMethodmethod該方法,並將該方法的回傳值MakeGenericType作為參數type,MethodBuilder並以代表T M()的物件作為參數 。 回傳值是 MethodInfo 你需要用來發出函式呼叫的物件。 程式碼範例展示了類似的情境。