Get name of class in C#
I need to g开发者_Go百科et the name of the class that I am currently in. The problem is that I am in a static property. Any idea how I can do this without a reference to this
?
If you really want it, although as TomTom points out, you might not need it:
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name
System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name
If you are in a static property, you should be able to make the type name a constant.
If you have a static property in a base class that is inherited, and you are trying to determine the type of the child class that you are in, you can't do this with a static property. The reason is that the static property is associated with the base class type, not any base class instance. Use a regular property instead, and use GetType().Name or similar.
The following call should give you the name of the current type...
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name
You can use something like:
public static class MyClass
{
public static string FullName
{
get { return typeof(MyClass).FullName; }
}
}
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString()
Which is mentioned over and over again, can be wrong if the Type is generic. It will not figure out the generic type.
class Generic<T>
{
public static string ClassName
{
[MethodImpl(MethodImplOptions.NoInlining)]
get
{
return System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
}
}
}
Also if you don't use the NoInlining
directive your code maybe inlined into the callsite which will definitely not yield the results you are after.
The following code will print Generic``1[T]
, rather than the particular instantiation it's being called from.
The solution is fairly obvious just use MakeGenericMethod
with T to get the right instance.
The solution is fairly obvious just use MakeGenericMethod with T to get the right instance.
But if you want to know the name of T you cannot use the MakeGenericMethod
. Another solution is to add a static class with a generic method:
public static class Helper
{
public static string GetName<T>()
{
Type type = typeof(T);
Type[] genericArguments = type.GetGenericArguments();
return string.Format("{0}<{1}>", type.Name, string.Join(",", genericArguments.Select(arg => arg.Name)));
}
}
No change the property ClassName
to
public static string ClassName
{
get
{
return Helper.GetName<Generic<T>>();
}
}
then you will get the correct generic name, for example a call to Generic<DateTime>.ClassName
will return
"Generic`1<DateTime>".
精彩评论