How to stop C# from replacing const variable with their values?

前端 未结 2 432
猫巷女王i
猫巷女王i 2020-12-28 11:28

We have a project that\'s compiled into a DLL called consts.dll that contains something like:

public static class Consts
{
    public const string a = \"a\";         


        
2条回答
  •  攒了一身酷
    2020-12-28 12:20

    I think usage of static readonly modifiers fits your needs:

    public static class Consts
    {
        public static readonly string a = "a";
        public static readonly string b = "b";
        public static readonly string c = "c";
    }
    

    Constants are hard-coded on the call-site, so that is your problem. Static readonly variable can be modified only in variable declaration or static constructor of Consts class, and it will not be inlined on the call-site.

提交回复
热议问题