获取没有完整命名空间的类型名称

问题描述 投票:0回答:6

我有以下代码:

return "[Inserted new " + typeof(T).ToString() + "]";

但是

 typeof(T).ToString()

返回包括命名空间的全名

有没有办法只获取类名(没有任何命名空间限定符?)

c# namespaces typeof
6个回答
658
投票
typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name

41
投票

尝试获取泛型类型的类型参数:

public static string CSharpName(this Type type)
{
    var sb = new StringBuilder();
    var name = type.Name;
    if (!type.IsGenericType) return name;
    sb.Append(name.Substring(0, name.IndexOf('`')));
    sb.Append("<");
    sb.Append(string.Join(", ", type.GetGenericArguments()
                                    .Select(t => t.CSharpName())));
    sb.Append(">");
    return sb.ToString();
}

也许不是最好的解决方案(由于递归),但它有效。输出看起来像:

Dictionary<String, Object>

12
投票

利用(类型属性

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;

10
投票

C# 6.0(含)之后可以使用 nameof 表达式:

using Stuff = Some.Cool.Functionality  
class C {  
    static int Method1 (string x, int y) {}  
    static int Method1 (string x, string y) {}  
    int Method2 (int z) {}  
    string f<T>() => nameof(T);  
}  

var c = new C()  

nameof(C) -> "C"  
nameof(C.Method1) -> "Method1"   
nameof(C.Method2) -> "Method2"  
nameof(c.Method1) -> "Method1"   
nameof(c.Method2) -> "Method2"  
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error  
nameof(Stuff) = "Stuff"  
nameof(T) -> "T" // works inside of method but not in attributes on the method  
nameof(f) -> “f”  
nameof(f<T>) -> syntax error  
nameof(f<>) -> syntax error  
nameof(Method2()) -> error “This expression does not have a name”  

注意!

nameof
无法获取底层对象的运行时类型,它只是编译时参数。如果方法接受 IEnumerable,则 nameof 仅返回“IEnumerable”,而实际对象可能是“List”。


9
投票
你可以这样做:
typeof(T).Name;

1
投票

您可以使用

Type.Name
属性仅获取类名,而无需命名空间限定符。

return "[Inserted new " + typeof(T).Name + "]";
© www.soinside.com 2019 - 2024. All rights reserved.