MethodBuilder.MakeGenericMethod(Type[]) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает универсальный метод, созданный из текущего определения универсального метода с помощью указанных аргументов универсального типа.
public:
override System::Reflection::MethodInfo ^ MakeGenericMethod(... cli::array <Type ^> ^ typeArguments);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")]
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
public override System.Reflection.MethodInfo MakeGenericMethod(params Type[] typeArguments);
public override System.Reflection.MethodInfo MakeGenericMethod(params Type[] typeArguments);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
public override System.Reflection.MethodInfo MakeGenericMethod(params Type[] typeArguments);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")>]
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")>]
override this.MakeGenericMethod : Type[] -> System.Reflection.MethodInfo
override this.MakeGenericMethod : Type[] -> System.Reflection.MethodInfo
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")>]
override this.MakeGenericMethod : Type[] -> System.Reflection.MethodInfo
Public Overrides Function MakeGenericMethod (ParamArray typeArguments As Type()) As MethodInfo
Параметры
Возвращаемое значение
Представляет MethodInfo универсальный метод, созданный из текущего определения универсального метода, используя указанные аргументы универсального типа.
- Атрибуты
Примеры
В следующем примере кода создается созданный метод из неполного определения универсального метода в неполном типе.
В примере создается временная сборка и модуль с одним типом, добавляется метод и делает метод Mуниверсальным путем добавления параметра типа T с помощью DefineGenericParameters метода. Параметр типа используется в качестве типа параметра метода, а также в качестве возвращаемого типа. Определение универсального метода не дано тексту, а закрытый тип не завершен. Затем метод MakeGenericMethod используется для создания созданного метода M<String> (M(Of String) в Visual Basic). В примере кода нет выходных данных, так как подкласс возвращаемого MethodInfoMakeGenericMethod методом не разрешает отражение по его параметрам.
Note
Другой пример кода, который используется MakeGenericMethod, см. в разделе DefineGenericParameters. MakeGenericMethod также широко используется при создании кода, использующего универсальные типы. См . практическое руководство. Определение универсального метода с использованием эмитирования отражения.
using System;
using System.Reflection;
using System.Reflection.Emit;
class Example
{
public static void Main()
{
// Define a transient dynamic assembly (only to run, not
// to save) with one module and a type "Test".
//
AssemblyName aName = new AssemblyName("MyDynamic");
AssemblyBuilder ab =
AppDomain.CurrentDomain.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.Run);
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name);
TypeBuilder tb = mb.DefineType("Test");
// Add a public static method "M" to Test, and make it a
// generic method with one type parameter named "T").
//
MethodBuilder meb = tb.DefineMethod("M",
MethodAttributes.Public | MethodAttributes.Static);
GenericTypeParameterBuilder[] typeParams =
meb.DefineGenericParameters(new string[] { "T" });
// Give the method one parameter, of type T, and a
// return type of T.
meb.SetParameters(typeParams);
meb.SetReturnType(typeParams[0]);
// Create a MethodInfo for M<string>, which can be used in
// emitted code. This is possible even though the method
// does not yet have a body, and the enclosing type is not
// created.
MethodInfo mi = meb.MakeGenericMethod(typeof(string));
// Note that this is actually a subclass of MethodInfo,
// which has rather limited capabilities -- for
// example, you cannot reflect on its parameters.
}
}
Imports System.Reflection
Imports System.Reflection.Emit
Class Example
Public Shared Sub Main()
' Define a transient dynamic assembly (only to run, not
' to save) with one module and a type "Test".
'
Dim aName As AssemblyName = New AssemblyName("MyDynamic")
Dim ab As AssemblyBuilder = _
AppDomain.CurrentDomain.DefineDynamicAssembly( _
aName, _
AssemblyBuilderAccess.Run)
Dim mb As ModuleBuilder = ab.DefineDynamicModule(aName.Name)
Dim tb As TypeBuilder = mb.DefineType("Test")
' Add a Public Shared method "M" to Test, and make it a
' generic method with one type parameter named "T").
'
Dim meb As MethodBuilder = tb.DefineMethod("M", _
MethodAttributes.Public Or MethodAttributes.Static)
Dim typeParams() As GenericTypeParameterBuilder = _
meb.DefineGenericParameters(New String() { "T" })
' Give the method one parameter, of type T, and a
' return type of T.
meb.SetParameters(typeParams)
meb.SetReturnType(typeParams(0))
' Create a MethodInfo for M(Of String), which can be used
' in emitted code. This is possible even though the method
' does not yet have a body, and the enclosing type is not
' created.
Dim mi As MethodInfo = _
meb.MakeGenericMethod(GetType(String))
' Note that this is actually a subclass of MethodInfo,
' which has rather limited capabilities -- for
' example, you cannot reflect on its parameters.
End Sub
End Class
Комментарии
При создании динамического кода может потребоваться вызвать метод, созданный из определения универсального метода, представленного в виде , MethodBuilderперед завершением заключиющего типа. Метод можно использовать MakeGenericMethod для создания MethodInfo такого созданного метода и использовать MethodInfo в созданном вызове.