Can a static field get the name of the class that its declared in?
Is it possible to refer to the name of the class that a piece of code is in?
For example w开发者_开发技巧hen adding logging statements with log4net we initialise the log like this in each class...
private static readonly ILog Log = LogManager.GetLogger(typeof(EmploymentCorrectionUpdate));
Where 'EmploymentCorrectionUpdate' is the name of the class containing the code.
It would be a lot easier if the class name could be retrieved generically.
Please Note: This is a static field.
this.GetType()
should do the trick, if you are not in a static context.
If you are in a static context, use
Type t = MethodBase.GetCurrentMethod().DeclaringType
(from .NET: Determine the type of “this” class in its static method)
yeah funny enough we use it for logging too, although I don't like using reflection for these purposes:
MethodInfo.GetCurrentMethod().DeclaringType.Name;
For an instance method it's easy (this.GetType()
), but you need a static, class-level method.
I think that's difficult (or slow). If there was an easy/quick way, the log4net developers would have used it.
You can use the below code for getting the class name.
MethodBase method = frame.GetMethod(); method.DeclaringType.Name
精彩评论