C# Inheritance: Static vs. Non-Static Field

前端 未结 3 1819
粉色の甜心
粉色の甜心 2021-01-23 14:51

I have a library base class (Controller) and three sub-classes that inherit from Controller (Sensor, Output, and Enviro

相关标签:
3条回答
  • 2021-01-23 15:24

    There would only be one static variable, however many subclasses you have. Is it meant to vary by subclass, or is it truly one global mapping? If it's the latter, then a static variable is appropriate. If not... well, there are various options, but you'd need to tell us what you're using the map for.

    0 讨论(0)
  • 2021-01-23 15:26

    Well, a private member won't be visible to your derived classes. You would need a protected member or property for that. Within the class, you can just refer to it as errorDescriptions or this.errorDescriptions.

    I'd be extremely wary of having a static, protected member variable that isn't thread safe and can be mutated by derived classes. That's just asking for trouble.

    0 讨论(0)
  • 2021-01-23 15:43

    If you only need one instance of the dictionary than yes, change it to protected static. Also you should use ConcurrentDictionary instead for thread safety.

    In the derived classes you access the field using Controller.errorDescription

    0 讨论(0)
提交回复
热议问题