MethodInfo.GetGenericMethodDefinition 方法

定义

返回一个 MethodInfo 对象,该对象表示可从其构造当前方法的泛型方法定义。

public virtual System.Reflection.MethodInfo GetGenericMethodDefinition ();
[System.Runtime.InteropServices.ComVisible(true)]
public virtual System.Reflection.MethodInfo GetGenericMethodDefinition ();

返回

一个 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);
    }
}
// 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);
// 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);

注解

泛型方法定义是可从中构造方法的模板。 例如,从泛型方法定义 T M<T>(T t) (用 C# 语法表示; Function M(Of T)(ByVal tVal As T) As T 在 Visual Basic) 可以在 Visual Basic) 中构造和调用方法 int M<int>(int t) (Function M(Of Integer)(ByVal tVal As Integer) As Integer 。 给定表示 MethodInfo 此构造方法的对象,该方法 GetGenericMethodDefinition 返回泛型方法定义。

如果从同一泛型方法定义创建两个构造的方法,则 GetGenericMethodDefinition 该方法将返回两个方法的同一 MethodInfo 对象。

如果在已表示泛型方法定义的 上MethodInfo调用 GetGenericMethodDefinition ,它将返回当前的 MethodInfo

如果泛型方法定义包括声明类型的泛型参数,则会有特定于每个构造类型的泛型方法定义。 例如,请考虑以下 C#、Visual Basic 和 C++ 代码:

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

generic <typename U, typename V> ref class B {};
generic <typename T> ref class C
{
public:
    generic <typename S> B<T,S>^ M() {...};
};

在 Visual Basic) C(Of Integer) 的构造类型 C<int> (中,泛型方法M返回 B<int, S>。 在打开类型 C<T>中, M 返回 B<T, S>。 在这两种情况下, IsGenericMethodDefinition 属性返回MethodInfotrue表示 的 M,因此MakeGenericMethod可以在两个 MethodInfo 对象上调用 。 对于构造的类型,调用 MakeGenericMethod 的结果是 MethodInfo 可以调用的 。 在打开类型的情况下, MethodInfo 无法调用 返回的 MakeGenericMethod

有关特定于泛型方法的术语的固定条件列表,请参阅 IsGenericMethod 属性。 有关泛型反射中使用的其他术语的固定条件列表,请参阅 IsGenericType 属性。

适用于

产品 版本
.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
.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 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅