我有以下代码:
我有以下代码:
return "[Inserted new " + typeof(T).ToString() + "]";
但是
typeof(T).ToString()
返回包括命名空间在内的完整名称
有没有办法只获取类名(不带任何命名空间限定符)?
我有以下代码:
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
Name
不考虑类型参数。 - gregsdennisthis.GetType().Name
、this.GetType().FullName
等。 - avenmore尝试使用以下方式获取泛型类型的类型参数:
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>
StringBuilder
,但却忽略了 string.Join
临时变量和 LINQ lambda。在你确定它是瓶颈之前,只需使用 String
即可。/抱怨 - Nigel Touch利用(类型属性)
Name Gets the name of the current member. (Inherited from MemberInfo.)
Example : typeof(T).Name;
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"。
nameof
不返回 Type
的名称。 - Nigel Touchnameof
返回 Type
的名称,以下是验证截图:http://prntscr.com/irfk2c - Stas Boyarincevtypeof(T).Name;
Type.Name
属性来获取只包含类名而不包含命名空间限定符的内容。return "[Inserted new " + typeof(T).Name + "]";
string1 + anything.ToString() + string2
是多余的。如果你写成string1 + anything + string2
,编译器会自动插入调用ToString
的代码。 - Tim RobinsonType
实例(由typeof(..)
返回)上有哪些属性,我相信你自己可以弄清楚这个问题。 - Peter LillevoldName
是MemberInfo
的成员,而MemberInfo
是Type
的基类。 - cathei