General CS question about constants

后端 未结 7 1375
旧巷少年郎
旧巷少年郎 2021-01-24 02:41

I\'m programming using C#, after programming on C. So I\'m using a lot of constants such as \"DEFAULT_USER_ID\", \"REMOTE_ADDRESS\" and such...

It seems to me that it\'s

7条回答
  •  故里飘歌
    2021-01-24 03:19

    Using constants for stuff like DEFAULT_USER_ID is still "the way to go" (unless you want it to be configurable, but that's another topic). --> const (C# Reference)

    Don't use constants for enumerations (FILE_TYPE_DOC = 1, FILE_TYPE_XLS = 2, ...). This can be done more elegantly in C# with enums:

    enum FileType {
       Doc,
       Xls,   // or, optionally, "Xls = 2".
       ...
    };
    

    You can also use this for flags (constants combinable by bitwise operators), which is another common use case of constants in C:

    [Flags]
    enum FontDecoration {
        None = 0,
        Bold = 1,
        Italic = 2,
        Underline = 4
    }
    

提交回复
热议问题