是否可以引用一段代码所在的类的名称?
例如,当使用log4net添加日志记录语句时,我们会在每个类中初始化这样的日志...
private static readonly ILog Log = LogManager.GetLogger(typeof(EmploymentCorrectionUpdate));
其中'EmploymentCorrectionUpdate'是包含代码的类的名称。
如果可以一般性地检索类名,那将会容易得多。
请注意:这是一个静态字段。
答案 0 :(得分:3)
this.GetType()
应该可以解决问题。
如果您处于静态环境中,请使用
Type t = MethodBase.GetCurrentMethod().DeclaringType
(来自.NET: Determine the type of “this” class in its static method)
答案 1 :(得分:2)
是的,有趣的是我们也用它来记录,虽然我不喜欢将反射用于这些目的:
MethodInfo.GetCurrentMethod().DeclaringType.Name;
答案 2 :(得分:1)
对于实例方法,它很容易(this.GetType()
),但是你需要一个静态的类级方法。
我认为这很困难(或很慢)。如果有一个简单/快速的方法,log4net开发人员会使用它。
答案 3 :(得分:0)
您可以使用以下代码获取课程名称。
MethodBase method = frame.GetMethod(); method.DeclaringType.Name