Прочитать на английском

Поделиться через


TypeBuilder.GetMethod(Type, MethodInfo) Метод

Определение

Возвращает метод указанного сконструированного универсального типа, соответствующего указанному методу определения универсального типа.

public static System.Reflection.MethodInfo GetMethod(Type type, System.Reflection.MethodInfo method);

Параметры

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 Disassembler) и сравнить его с кодом, созданным классом Example.

Код в классе Example демонстрирует использование метода для создания универсального GetMethod кода. Метод Main класса Example создает динамическую сборку, содержащую класс с именем Sample , и использует DefineGenericParameters метод , чтобы сделать его универсальным путем добавления параметра типа с именем T. Конструктор без параметров и поле с именем Fieldс типом Tдобавляются в класс Sample. Метод GM добавляется и преобразуется в универсальный метод с помощью MethodBuilder.DefineGenericParameters метода . Параметр типа имеет GM имя U. После определения параметра type сигнатура GM добавляется с помощью MethodBuilder.SetSignature метода . Не существует возвращаемого типа и обязательных или настраиваемых модификаторов, поэтому все параметры этого метода за null исключением parameterTypes; parameterTypes задает тип единственного параметра Uметода в значение , параметр универсального типа метода. Тело метода создает экземпляр сконструированного типа Sample<U> (Sample(Of U) в Visual Basic), назначает параметр Fieldметода , а затем выводит значение Field. Для хранения метода Mainточки входа определен фиктивный тип . В теле статический метод вызывается для созданного универсального Mainтипа Sample<int> (Sample(Of Integer) в Visual Basic) с заменой Uтипа String .GM Метод GetMethod используется для создания MethodInfo для статического GM метода созданного универсального типа Sample<U>, а 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.");
    }
}

Комментарии

Метод GetMethod предоставляет способ получения объекта , представляющего MethodInfo метод созданного универсального типа, определение универсального типа которого представлено TypeBuilder объектом .

Например, предположим, что у вас есть TypeBuilder объект , представляющий тип G<T> в синтаксисе C# (G(Of T) в Visual Basic, generic <T> ref class G в C++), и MethodBuilder объект , представляющий метод T M() в синтаксисе C# (Function M() As T в Visual Basic, T M() в C++), который определен в G<T>. Предположим, что G<T> имеет универсальный метод с параметром U типа, который создает экземпляр созданного типа G<U> и вызывает метод M для этого экземпляра. Чтобы вызвать функцию, нужен MethodInfo объект , который представляет M для созданного типа, иными словами, возвращающий тип U , а не тип T. Для этого сначала вызовите MakeGenericType метод для TypeBuilder объекта , указав GenericTypeParameterBuilder объект, который представляет U в качестве аргумента типа. Затем вызовите GetMethod метод с возвращаемым значением метода в MakeGenericType качестве параметра type и MethodBuilder объектом , который представляет T M() как параметр method. Возвращаемое значение — это объект, необходимый MethodInfo для вызова функции. В примере кода демонстрируется сценарий, аналогичный этому.

Применяется к

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided), 2.1