繁体   English   中英

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

[英]Get type name without full namespace

我有以下代码:

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

 typeof(T).ToString()

返回包括命名空间的全名

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

typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name

试试这个来获取泛型类型的类型参数:

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>

使用( 类型属性

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

在 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”。

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

我有以下代码:

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

 typeof(T).ToString()

返回全名,包括名称空间

无论如何,有没有要获取类名(没有任何名称空间限定符?)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM