.net c#类级字符串常量与方法级字符串常量

class-level string constants vs method-level string constants
2021-11-25
  •  译文(汉语)
  •  原文(英语)

类级字符串常量与方法级字符串常量之间是否存在显着差异.编译器会识别常量并应用常量折叠吗?还是总是会创建 nw 对象?

这是示例:类级常量

class A
    {
        private const string Sid = "sid";
        private const string Pid = "pid";

        public void Do()
        {
            Console.WriteLine(Sid);
            Console.WriteLine(Pid);
        }
    }

方法级常量:

class B
    {
        public void Do()
        {
            const string Sid = "sid";
            const string Pid = "pid";

            Console.WriteLine(Sid);
            Console.WriteLine(Pid);
        }
    }
解决过程1

字符串常量是较新的"内联"*,因为它们是真正的对象.编译器将始终合并添加在一起的相同字符串常量的部分(即"a"+"b"与指定"ab"相同).

字符串常量也可以"内嵌" - 意味着相同值的所有常量都引用相同的实际字符串对象(据我所知,C# 编译器总是这样做).

数字常量可以"内联"到它们使用的地方,除了总是在编译时尽可能多地计算(即 2*2*4 与指定 16 相同).

要实现"共享常量"行为,需要使用readonly字段而不是const.

*"内联"直接放入结果代码中,而不是引用共享值.

解决过程2

常量之间的区别在于范围 - 就像非常量声明一样,要考虑的主要事情是可以从哪里访问这些值.现在,哪个声明更干净已经无关紧要,以至于值得一场史诗般的火焰战争......

are there any significant difference between class-level string constants vs method level string constants. Will compiler recognize constants and apply constant folding? Or nw object always will be created?

Here is example: class-level consts

class A
    {
        private const string Sid = "sid";
        private const string Pid = "pid";

        public void Do()
        {
            Console.WriteLine(Sid);
            Console.WriteLine(Pid);
        }
    }

Method-level constants:

class B
    {
        public void Do()
        {
            const string Sid = "sid";
            const string Pid = "pid";

            Console.WriteLine(Sid);
            Console.WriteLine(Pid);
        }
    }
Solutions1

String constants are newer "inlined"* because they are true objects. Compiler will always merge parts of the same string constant added together (i.e. "a"+"b" is identical to specifying "ab").

String constants also can "interned" - meaning all constants of the same value are referring to the same actual string object (To my knowledge C# compiler always does that).

Numeric constants can be "inlined" into places where they are used in addition to always computed as much as possible at compile time (i.e. 2*2*4 is identical to specifying 16).

To achieve "shared constant" behavior one need to use readonly fields instead of const.

*"inline" as placed into resulting code directly instead of referencing a shared value.

Solutions2

The difference between the constants is in scope - just as with a non-const declaration, the main thing to consider is from where these values can be accessed. Now, which declaration is cleaner is irrelevant enough to be worthy of an epic flame war...

转载于:https://stackoverflow.com/questions/15237428/class-level-string-constants-vs-method-level-string-constants

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入