Is it possible to have a getter for a const?

前端 未结 4 1970
忘掉有多难
忘掉有多难 2020-12-19 06:16

Just curious, is there a way to have a getter for a constant variable? I have a sort of internal version number to ensure that two versions of a library are still speaking t

4条回答
  •  没有蜡笔的小新
    2020-12-19 07:05

    You have to keep in mind the reason for the existance of getters/setters. It is to control access to an encapsulated variable, specifically to control how a variable is changed and who can change it. Since a const is set only once and remains read-only on runtime there is no reason to create a property for it. Setting the constant to public is completely acceptable since it is not a private variable that needs to be protected.

    If you really... really want to make it a property then just define it as a readonly property, skip the setter entirely:

    public Int16 ProtocolVersion { get { return protocol_version; } }
    

    But just so we are clear, I would say normally you would have public constants with the same coding style as properties:

    public const Int16 ProtocolVersion = 1
    

提交回复
热议问题