C# protected property or field

后端 未结 5 1383
离开以前
离开以前 2021-01-01 13:47

Do you think it\'s better to always make protected class members an auto-implemented protected property to keep isolation or make it protected field is enough?



        
5条回答
  •  死守一世寂寞
    2021-01-01 13:56

    I know this question is old, but I would answer it based on the scope of the value as well as where it needs to be initialized or written to. I try to use the tightest scope possible. Hopefully the following will make it more clear on how to decide:

    Protected values: This assumes the value only needs to be accessed by the base class and/or the inheriting class, and not by any outside code...

    1. When the inheriting class has to read, but never has to modify the value:

      • If the value can be written once in the constructor of the base class, use the following, which prevents the inheriting class from writing to it, and goes a step further and only allows it to be set in the constructor:

        protected readonly bool test;

      • If the value can be written to in a different method other than the constructor, but still only in the base class, use the following, which prevents the inheriting class from writing to it, but allows it to read:

        protected bool Test { get; private set; }

    2. When the inheriting class can modify the value, use the following, which allows both the inheriting class and the base class to write to it at any point:

      protected bool test;

    Private values: This assumes the value only needs to be accessed from within the class it is declared in.

    1. If it can only be set once in the constructor, use:

      readonly bool test;

    2. If it can be set anywhere in the class, use:

      bool test;

    Also, don't forget that if you declare it as a property, it should use PascalCase. If you declare it as a member variable, it should use camelCase. This will make it easier for other developers to understand the scope.

提交回复
热议问题