C# private, static, and readonly

前端 未结 9 748
忘掉有多难
忘掉有多难 2020-12-25 12:27

I was reviewing some code for log4net and I came across this.

private static readonly ILog logger = LogManager.GetLogger(typeof(AdminClient));
9条回答
  •  庸人自扰
    2020-12-25 13:21

    The reason to put a readonly flag on a private variable is to declare that the variable will always reference the same object. It's true that being private makes it invisible to anyone outside the class, but this way we can make sure we didn't accidentaly overwrite the variable with a new object, by writing something like

    logger = LogManager.GetLogger(typeof(AdminClient));
    

    somewhere else in our class. With readonly it just won't compile (Unless it was not initialized before, and we are in the (static) constructor)

提交回复
热议问题