Declaring strings public static readonly versus public const versus public static const

后端 未结 5 1698
故里飘歌
故里飘歌 2021-02-01 02:47

In each project we have there is a file used to store the various SQL statements used in that project. There are a handful of variations on how the class is declared and how the

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 03:09

    Speedwise the difference between public static string and public const string is negligible.

    In IL it's a difference between

    ldsfld someaddr.field 
    

    and

    ldstr "your const here"
    

    Here lies the answer though. By using const you're literally make your assembly to use that literal every time you use it, so the assembly will be ridden with those literals. With static the will be "pointers" to the central location.

    The biggest gotcha lies in the following: you can't perfrom switch case against static strings, but you can against const (as you should).

    So, my take on this: if you need to use switch - you have to use use const; if you don't - I'd prolly go with static.

    HTH

    Nikolai

提交回复
热议问题