有什么方法可以使用泛型参数获取当前正在执行的泛型方法吗?

Is there any way to get current executing generic method with generic arguments?

所以,假设我有 class

public class Sample<T>
{
    // (1)
    public static void StaticMethod1() {
        
    }

    // (2)
    public static T2 StaticMethod2<T2>() where T2 : new() {
        return new T2();
    }

    // (3)
    public void InstanceMethod1() {
        
    }
    
    // (4)
    public T2 InstanceMethod2<T2>() where T2: new () {
        return new T2();
    }
}

我想获得具有具体通用参数的方法:

  1. T
  2. T, T2
  3. T
  4. T, T2

所以,现在,我只知道如何通过第三种方法获得我需要的东西 GetType().GetMethod("InstanceMethod1) 因为 GetType returns 类型带有通用参数(但不能在静态上下文中调用),但在其他情况下如何做?有什么办法吗?

您似乎想用具体的通用参数构造 Sample<>。您可以为此使用 MakeGenericType

var concreteType = typeof(Sample<>).MakeGenericType(new []{typeof(SomeConcreteType)})

然后你可以使用GetMethodMakeGenericMethod:

var concreteMethod = concreteType.GetMethod("InstanceMethod2").MakeGenericMethod(new []{ typeof(SomeType2) });

UPD

要执行您在评论中描述的操作,您需要在相应位置使用 typeof(T)typeof(T2)

public class Gen<T>
{
    public void Test<T1>() => Console.WriteLine($"<{typeof(T)}> - <{typeof(T1)}>");
}

new Gen<int>().Test<string>(); // prints <System.Int32> - <System.String>