给定一个泛型,包括
List<string>
Nullable<Int32>
如何获得 C# 的通用名称?
var t = typeof(Nullable<DateTime>);
var s = t.GetGenericTypeDefinition().Name + "<" + t.GetGenericArguments()[0].Name + ">";
这会产生 "Nullable`1<DateTime>"
, 但我需要 "Nullable<DateTime>"
.
最佳答案
我看到您已经接受了一个答案,但老实说,如果您只是将其中的内容与您已经编写的内容结合起来,那么这个答案将不足以可靠地完成此操作。它走在正确的轨道上,但您的代码将只适用于只有一个泛型参数的泛型类型,并且只有当泛型类型参数本身不是泛型时它才会工作!
这是一个在所有情况下都应该有效的函数(写成扩展方法):
public static class TypeExtensions
{
public static string ToGenericTypeString(this Type t)
{
if (!t.IsGenericType)
return t.Name;
string genericTypeName = t.GetGenericTypeDefinition().Name;
genericTypeName = genericTypeName.Substring(0,
genericTypeName.IndexOf('`'));
string genericArgs = string.Join(",",
t.GetGenericArguments()
.Select(ta => ToGenericTypeString(ta)).ToArray());
return genericTypeName + "<" + genericArgs + ">";
}
}
这个函数是递归的并且是安全的。如果您在此输入上运行它:
Console.WriteLine(
typeof(Dictionary<string, List<Func<string, bool>>>)
.ToGenericTypeString());
你得到这个(正确的)输出:
Dictionary<String,List<Func<String,Boolean>>>
关于c# - 给定一个类型实例,如何在 C# 中获取泛型类型名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2448800/