In C#
,我有一个具有以下签名的方法:
List<T> Load<T>(Repository<T> repository)
Inside Load()
方法,我想转储完整的方法名称(用于调试目的),包括泛型类型。例如:打电话Load<SomeRepository>();
会写"Load<SomeRepository>"
到目前为止我尝试过的:使用MethodBase.GetCurrentMethod()
and 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;
}
检索方法名称有效,但对于通用参数,它总是返回我"T"
。方法返回Load<T>
代替Load<SomeRepository>
(这是没用的)
我试过打电话GetGenericArguments()
外部GetMethodName()
并将其作为参数提供,但没有帮助。
我可以提供typeof(T)
作为参数GetMethodName()
(它会起作用)但随后它将特定于泛型类型的数量,例如:Load<T, U>
除非我提供其他论点,否则它将不再起作用。
的答案是杰佩·斯蒂格·尼尔森 https://stackoverflow.com/a/19113261/2042090根据您的要求是正确的。事实上,你的解决方案返回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>);
}
}
这是您要求的输出:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)