Windows 存储应用程序 .NET GetCurrentMethod().DeclaringType 替代方案

Windows store app .NET GetCurrentMethod().DeclaringType alternative

完全坚持这个...我遇到了这个问题,我们在 Unity 项目中使用 log4Net 来构建 Windows 商店应用程序。 log4Net 需要声明记录器的 classes 类型或名称(作为字符串)。由于 Windows 商店 .NET 被修改,它没有像 GetCurrentMethod() 这样的常用方法...我检查了一下,到目前为止它是无望的:

通常的做法是这样

public sealed class SomeClassController : ApiController
{
    private static readonly ILog Log = 
        LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
...

How to get method name win 8 app - 此处提供的解决方案不起作用,因为属性 [CallerMememberName] return 调用者(而非声明者)。 func(Expression expression) 方法不起作用,因为它仅在方法内部使用时才起作用,而不是作为 class 字段(在 log4Net 中正是这种情况)。

另一种可能性是使用 StackFrame,但是 "luckily" Windows 商店也不支持它,进入 StackTrace 的唯一方法是通过异常,这不是一个选项因为 1. Is 真的很慢 2. 必须在 Unity 生产中删除所有异常抛出。

像 GetType() 这样的简单解决方案不起作用,因为如果继承了 classes,它们就会被覆盖。更多信息 - http://rundevrun.blogspot.lt/2012/11/gettype-vs-methodbasegetcurrentmethodde.html

我 运行 无法选择,在 class 字段中使用时是否无法获取 DeclaringType???

只需使用 typeof - 它更简单,并且不需要任何框架支持:

public sealed class SomeClassController : ApiController
{
    private static readonly ILog Log = 
        LoggerManager.GetLogger(typeof(SomeClassController));
    ...
}

唯一的缺点是,如果您将其复制并粘贴到其他地方,您将最终记录错误 class。您可以通过以下方式缓解这种情况:

  • 编写 Roslyn 代码分析器(或类似工具)来发现问题
  • 小心代码审查
  • 预发布流程步骤为 "Find all calls to LoggerManager.GetLogger and review them"