C# any way of accessing the class name of a static class via code?
Within a static class you cannot use the keyword "this" so I can't call this.GetType().GetFullName
if I have
public static class My.Library.Class
{
public static string GetName()
{
}
}
Is there anything I can call from within GetName that will ret开发者_如何学运维urn My.Library.Class
you can get the type of a predetermined class with:
typeof(My.Library.Class).FullName
If you need "the class that declares this method", you'll need to use
MethodBase.GetCurrentMethod().DeclaringType.FullName
However, there's a chance this method will be inlined by the compiler. You can shift this call to the static constructor / initialiser of the class (which will never be inlined - log4net recommends this approach):
namespace My.Library
public static class Class
{
static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName;
public static string GetName()
{
return className;
}
}
}
Applying [MethodImpl(MethodImplOptions.NoInlining)]
might help, but you should really read up on that if you considering it
HTH - Rob
MethodBase.GetCurrentMethod().DeclaringType.FullName
typeof(My.Library.Class).FullName
精彩评论