问题描述
在
我可以提供 typeof(T)作为 GetMethodName() code>(它会起作用),但它会针对泛型类型的数量,例如:with Load< T,U> 它不会工作,除非我提供了另一个参数。
在您的要求方面是正确的。事实上,您的解决方案返回 T ,并且他返回运行时类型名称。如果你要求不同的东西,那就试着重写你的问题。下面是一个通用项目的另一个解决方案:
using System;
使用System.Collections.Generic;
使用System.Linq;
类程序
{
static void Main()
{
Load(new Repository< int>());
Load(new Repository< string>());
Console.ReadLine();
}
类存储库< T> {}
静态列表< T> Load< T>(Repository< T> repository)
{
Console.WriteLine(Debug:List< {1}> Load< {1}>({0}< {1} (Repository< T>),typeof(Repository< T>)。
返回默认值(List< T>);
$ / code $ / pre
以下是你要求的输出: p>
In C#, I have a method with the following signature :
List<T> Load<T>(Repository<T> repository)Inside Load() method, i'd like to dump full method name (for debugging purposes), including the generic type. eg : calling Load<SomeRepository>(); would write "Load<SomeRepository>"
What i have try so far : using MethodBase.GetCurrentMethod() and GetGenericArguments() to retrieve information.
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; }Retrieving method name works, but for generic parameter it always return me "T". Method returns Load<T> instead of Load<SomeRepository> (which is useless)
I have tried to call GetGenericArguments() outside GetMethodName() and provide it as argument but it doesn't help.
I could provide typeof(T) as a parameter of GetMethodName() (it will works) but then it will be specific to number of generic types eg : with Load<T, U> it would not work anymore, unless I provide the other argument.
解决方案The answer of Jeppe Stig Nielsen is correct in terms of your requirements. In fact, your solution returns T and his returns the runtime type name. If you ask for something different, then try to rewrite your question. The below is another solution for one generic item:
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>); } }Here is the output that you asked for:
这篇关于如何检索泛型方法的名称,包括泛型类型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!