如何检索泛型方法的名称,包括泛型类型名称

tig*_*rou 6 c# generics reflection

C#,我有一个方法具有以下签名:

List<T> Load<T>(Repository<T> repository) 
Run Code Online (Sandbox Code Playgroud)

在Inside Load()方法中,我想转储完整的方法名称(用于调试目的),包括泛型类型.例如:打电话Load<SomeRepository>();会写"Load<SomeRepository>"

到目前为止我尝试过:使用MethodBase.GetCurrentMethod()GetGenericArguments()检索信息.

List<T> Load<T>(Repository<T> repository) 
{
   Debug.WriteLine(GetMethodName(MethodBase.GetCurrentMethod()));
}

string GetMethodName(MethodBase method)
{
     Type[] arguments = method.GetGenericArguments();
     if (arguments.Length > 0)
        return string.Format("{0}<{1}>", 
          method.Name, string.Join(", ", arguments.Select(x => x.Name)));
     else
        return method.Name;
}
Run Code Online (Sandbox Code Playgroud)

检索方法名称有效,但对于通用参数,它总是返回我"T".方法返回Load<T>而不是Load<SomeRepository>(这是无用的)

我试图在GetGenericArguments()外面打电话GetMethodName()并提供它作为参数,但它没有帮助.

我可以提供(它将起作用)typeof(T)的参数GetMethodName()但是它将特定于泛型类型的数量,例如:Load<T, U>它将不再起作用,除非我提供另一个参数.

Rys*_*gan 1

就您的要求而言,杰普·斯蒂格·尼尔森的答案是正确的。事实上,您的解决方案返回T,而他的解决方案返回运行时类型名称。如果您要求不同的东西,请尝试重写您的问题。以下是针对一个通用项目的另一种解决方案:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Load(new Repository<int>());
        Load(new Repository<string>());
        Console.ReadLine();
    }

    class Repository<T> { }

    static List<T> Load<T>(Repository<T> repository)
    {
        Console.WriteLine("Debug: List<{1}> Load<{1}>({0}<{1}> repository)", typeof(Repository<T>).Name, typeof(Repository<T>).GenericTypeArguments.First());
        return default(List<T>);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是您要求的输出:

在此输入图像描述