'Static readonly' vs. 'const'

前端 未结 18 2913
旧巷少年郎
旧巷少年郎 2020-11-22 04:07

I\'ve read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things

18条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:07

    There is one important question, that is not mentioned anywhere in the above answers, and should drive you to prefer "const" especially for basic types like "int", "string" etc.

    Constants can be used as Attribute parameters, static readonly field not!

    Azure functions HttpTrigger, not using HttpMethods class in attribute

    If only microsoft used constants for Http's GET, POST, DELETE etc.

    It would be possible to write

    [HttpTrigger(AuthorizationLeve.Anonymous,  HttpMethods.Get)] // COMPILE ERROR: static readonly, 
    

    But instead I have to resort to

    [HttpTrigger(AuthorizationLeve.Anonymous,  "GET")] // STRING
    

    Or use my own constant:

    public class HttpConstants
    {
        public const string Get = "GET";
    }
    
    [HttpTrigger(AuthorizationLeve.Anonymous,  HttpConstants.Get)] // Compile FINE!
    

提交回复
热议问题