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


MethodInfo.GetGenericMethodDefinition Метод

Определение

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

public:
 virtual System::Reflection::MethodInfo ^ GetGenericMethodDefinition();
public virtual System.Reflection.MethodInfo GetGenericMethodDefinition();
[System.Runtime.InteropServices.ComVisible(true)]
public virtual System.Reflection.MethodInfo GetGenericMethodDefinition();
abstract member GetGenericMethodDefinition : unit -> System.Reflection.MethodInfo
override this.GetGenericMethodDefinition : unit -> System.Reflection.MethodInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetGenericMethodDefinition : unit -> System.Reflection.MethodInfo
override this.GetGenericMethodDefinition : unit -> System.Reflection.MethodInfo
Public Overridable Function GetGenericMethodDefinition () As MethodInfo

Возвращаемое значение

MethodInfo Объект, представляющий определение универсального метода, из которого можно создать текущий метод.

Атрибуты

Исключения

Текущий метод не является универсальным методом. То есть IsGenericMethod возвращается false.

Этот метод не поддерживается.

Примеры

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

Этот пример является частью более крупного примера, предоставленного MakeGenericMethod для метода.

// Define a class with a generic method.
public class Example
{
    public static void Generic<T>(T toDisplay)
    {
        Console.WriteLine("\r\nHere it is: {0}", toDisplay);
    }
}
' Define a class with a generic method.
Public Class Example
    Public Shared Sub Generic(Of T)(ByVal toDisplay As T)
        Console.WriteLine(vbCrLf & "Here it is: {0}", toDisplay)
    End Sub
End Class
// Create a Type object representing class Example, and
// get a MethodInfo representing the generic method.
//
Type ex = typeof(Example);
MethodInfo mi = ex.GetMethod("Generic");

DisplayGenericMethodInfo(mi);

// Assign the int type to the type parameter of the Example
// method.
//
MethodInfo miConstructed = mi.MakeGenericMethod(typeof(int));

DisplayGenericMethodInfo(miConstructed);
' Create a Type object representing class Example, and
' get a MethodInfo representing the generic method.
'
Dim ex As Type = GetType(Example)
Dim mi As MethodInfo = ex.GetMethod("Generic")

DisplayGenericMethodInfo(mi)

' Assign the Integer type to the type parameter of the Example 
' method.
'
Dim arguments() As Type = { GetType(Integer) }
Dim miConstructed As MethodInfo = mi.MakeGenericMethod(arguments)

DisplayGenericMethodInfo(miConstructed)
// Get the generic type definition from the closed method,
// and show it's the same as the original definition.
//
MethodInfo miDef = miConstructed.GetGenericMethodDefinition();
Console.WriteLine("\r\nThe definition is the same: {0}",
    miDef == mi);
' Get the generic type definition from the constructed method,
' and show that it's the same as the original definition.
'
Dim miDef As MethodInfo = miConstructed.GetGenericMethodDefinition()
Console.WriteLine(vbCrLf & "The definition is the same: {0}", _
    miDef Is mi)

Комментарии

Определение универсального метода — это шаблон, из которого можно создать методы. Например, из определения T M<T>(T t) универсального метода (выраженного в синтаксисе C#; Function M(Of T)(ByVal tVal As T) As T в Visual Basic) можно создать и вызвать метод int M<int>(int t) (Function M(Of Integer)(ByVal tVal As Integer) As Integer в Visual Basic). MethodInfo Учитывая объект, представляющий этот созданный метод, GetGenericMethodDefinition метод возвращает определение универсального метода.

Если два созданных метода создаются из одного определения универсального метода, GetGenericMethodDefinition метод возвращает один и тот же MethodInfo объект для обоих методов.

Если вы вызываете GetGenericMethodDefinitionMethodInfo определение универсального метода, оно возвращает текущее MethodInfoзначение.

Если определение универсального метода включает универсальные параметры декларающего типа, будет определение универсального метода, определенное для каждого созданного типа. Например, рассмотрим следующий код:

class B<U,V> {}
class C<T> { public B<T,S> M<S>() {...}}
Class B(Of U, V)
End Class
Class C(Of T)
    Public Function M(Of S)() As B(Of T, S)
        ...
    End Function
End Class

В созданном типе C<int> (C(Of Integer)в Visual Basic) возвращается B<int, S>универсальный методM. В открытом типе C<T>M возвращаетсяB<T, S>. В обоих случаях свойство возвращается true для представляемого MethodInfoMобъекта, поэтому MakeGenericMethod его можно вызвать для обоих IsGenericMethodDefinitionMethodInfo объектов. В случае созданного типа результат вызова MakeGenericMethod — это MethodInfo вызов, который можно вызвать. В случае открытого типа MethodInfo возвращаемый MakeGenericMethod не может вызываться.

Список инвариантных условий терминов, относящихся к универсальным методам, см. в свойстве IsGenericMethod . Список инвариантных условий для других терминов, используемых в универсальном отражении, см. в свойстве IsGenericType .

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

См. также раздел