开发者

Any reason why log field should private static?

开发者 https://www.devze.com 2023-01-13 23:43 出处:网络
here is in C#: private static readonly ILog log = LogManager.GetLogger(typeof (MyClass)); Not only 开发者_运维百科in C# but another language i saw the same..

here is in C#:

private static readonly ILog log = LogManager.GetLogger(typeof (MyClass));

Not only 开发者_运维百科in C# but another language i saw the same.. any thought?


It's private because other classes should not access MyClass' log.

It's static because it doesn't depend on the class instance. (And so that it can be used by static methods)


So that the field isn't inherited by your sub-classes.

Take this example:

class BaseFoobar
{
   public static readonly ILog log = LogManager.GetLogger(typeof(BaseFoobar));
}

class SpecializedFoobar : BaseFoobar
{
   public void Whatever()
   {
      log.Error("I exploded");
   }
}

If SpecializedFoobar's Whatever() function is ever called the co-responding log would be invalid:

[MyApp.BaseFoobar]: ERROR: I exploded

0

精彩评论

暂无评论...
验证码 换一张
取 消