C# 是否可以使用反射获取当前正在执行的类名?

C# 是否可以使用反射获取当前正在执行的类名?,c#,reflection,C#,Reflection,我正在编写一个日志类,希望能够获取调用Helper.Log(字符串消息)的类的名称 使用反射和c#这可能吗?是的,这很容易 Helper.Log("[" + this.GetType().Name + "]: " + message); 请注意,如果您的logger类实际上是日志框架(如log4net或NLog)的包装器,那么可以将日志框架配置为获取调用类/方法。要使其正常工作,必须正确包装日志框架。对于NLog和log4net,正确包装(保留呼叫站点信息)通常涉及使用“日志”方法(而不是错误

我正在编写一个日志类,希望能够获取调用
Helper.Log(字符串消息)
的类的名称

使用反射和c#这可能吗?

是的,这很容易

Helper.Log("[" + this.GetType().Name + "]: " + message);

请注意,如果您的logger类实际上是日志框架(如log4net或NLog)的包装器,那么可以将日志框架配置为获取调用类/方法。要使其正常工作,必须正确包装日志框架。对于NLog和log4net,正确包装(保留呼叫站点信息)通常涉及使用“日志”方法(而不是错误、警告、信息等变体)并将“记录器类型”作为第一个参数传递。“logger type”是封装日志框架的记录器的记录器类型

这里有一种包装NLog()的方法:

下面是使用log4net的方法:

class MyLogger    
{        
  private ILog _logger;        
  public MyLogger(string name)        
  {            
    _logger = LogManager.GetLogger(name);        
  }        
  public void WriteMessage(string message)                 
  {            
    // Call the Log() method. It is important to pass typeof(MyLogger) as the      
    // first parameter. If you don't, ${callsite} and other callstack-related             
    // formatters will not work properly.            
    //
    _logger.Log(typeof(MyLogger), LogLevel.Info, message);
  }    
}
有关静态方法,请参见
class MyLogger    
{        
  private ILog _logger;        
  public MyLogger(string name)        
  {            
    _logger = LogManager.GetLogger(name);        
  }        
  public void WriteMessage(string message)                 
  {            
    // Call the Log() method. It is important to pass typeof(MyLogger) as the      
    // first parameter. If you don't, ${callsite} and other callstack-related             
    // formatters will not work properly.            
    //
    _logger.Log(typeof(MyLogger), LogLevel.Info, message);
  }    
}