如果我的方法签名像这样:
public string myMethod<T>( ... )
在方法内部,我如何获取作为类型参数给定的类型的名称? 我想要做一些类似于 typeof(T).FullName
的事情,但实际上并不起作用...
您的代码应该可以工作。 typeof(T).FullName
是完全有效的。 这是一个完全编译,运行的程序:
using System;
class Program
{
public static string MyMethod<T>()
{
return typeof(T).FullName;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod<int>());
Console.ReadKey();
}
}
System.Int32
<int?>
" 吗?如果是,它可以工作,但是你会得到 System.Nullable<int>
(完整名称语法),这是你所期望的... - Reed Copseynameof(T)
和typeof(T).Name
会得到相同的结果,所以这篇文章对我很有帮助。结果发现nameof(T)
只返回T
。 - dahvyd这个扩展方法输出非泛型类型的简单类型名称,并为泛型类型附加泛型参数列表。对于不需要担心内部泛型参数的情况,例如IDictionary<int,IDictionary<int,string>>
,这种方法很有效。
using System;
using System.Linq;
namespace Extensions
{
public static class TypeExtensions
{
/// <summary>
/// Returns the type name. If this is a generic type, appends
/// the list of generic type arguments between angle brackets.
/// (Does not account for embedded / inner generic arguments.)
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.String.</returns>
public static string GetFormattedName(this Type type)
{
if(type.IsGenericType)
{
string genericArguments = type.GetGenericArguments()
.Select(x => x.Name)
.Aggregate((x1, x2) => $"{x1}, {x2}");
return $"{type.Name.Substring(0, type.Name.IndexOf("`"))}"
+ $"<{genericArguments}>";
}
return type.Name;
}
}
}
string.Join(",", type.GetGenericArguments().Select(GetFormattedName))
。 - Jeremy Lakemantypeof(T).Name
和typeof(T).FullName
对我有效,我得到了作为参数传递的类型。
你的代码应该能够正常工作。你也可以获取类的名称而不包括命名空间的完整名称,例如:
using System;
namespace ConsoleApp1
{
class Program
{
public static string GettingName<T>() => typeof(T).Name;
public static string GettingFullName<T>() => typeof(T).FullName;
static void Main(string[] args)
{
Console.WriteLine($"Name: {GettingName<decimal>()}");
Console.WriteLine($"FullName: {GettingFullName<decimal>()}");
}
}
}
Name: Decimal
FullName: System.Decimal
var t = new T();
var name = t.GetType().FullName;
private static string ExpandTypeName(Type t) =>
!t.IsGenericType || t.IsGenericTypeDefinition
? !t.IsGenericTypeDefinition ? t.Name : t.Name.Remove(t.Name.IndexOf('`'))
: $"{ExpandTypeName(t.GetGenericTypeDefinition())}<{string.Join(',', t.GetGenericArguments().Select(x => ExpandTypeName(x)))}>";
.Select(ExpandTypeName)
。 - kofifus
typeof(T).FullName
应该可以工作。但实际发生了什么? - Nathan Taylor