Effective C#阅读笔记-2.使用readonly而不是const变量
来源:互联网 发布:suse mysql rpm 安装 编辑:程序博客网 时间:2024/06/05 11:01
readonly常量为运行时常量,const常量为编译时常量;编译时常量会在编译时,所有引用编译时常量的地方都会被替换为编译时常量的值,(编译时常量只能用于numbers 和strings, enums类型);运行时常量的值是在运行时确定的。当你引用一个只读常量时(read-only)IL会为你引用一个运行时常量的变量,而不是直接使用该值,可以是任何类型。
使用编译是常量的限制:编译时常量只能用于numbers 和strings, enums类型(primitive types ),因为只有这些类型才能在编译为IL时替换为字符value。不能使用new 来初始化一个编译时常量即使,这个常量是一个primitive types;相反运行是常量可以为任何类型,运行时常量可以使用初始化构造器赋值或者在类构造函数赋值,在其他地方不允许修改运行时常量,编译会无法通过。
1.编译时常量,申明时就是静态常量,可以通过类直接访问;运行时常量可以申明为实例常量;
class Program { static void Main(string[] args) { Console.WriteLine(ConstClass.EMD); } class ConstClass { public const int EMD = 2004; } }
2.运行时常量,引用的是变量,而不是变量的值,编译时常量正好想法,会在编译时用值替换。如果一个assemble a中引用的另外一个assemble b中的编译时常量,正好 assemble b编译时常量发生了改变,重新编译了,assemble a程序集没有重新编译,会出现不一致,可能会导致严重后果;
3.编译时常量带来的是性能的提升,运行时常量带来的是灵活性;
The final advantage of using const over readonly is performance: Known constant values can generate slightly more efficient code than the variable accesses necessary for readonly values. However, any gains are slight and should be weighed against the decreased flexibility. Be sure to profile performance differences before giving up the flexibility.
4.几个场景是必须使用编译时常量的,编译时需要访问的变量值;属性的参数;enum定义;
const must be used when the value must be available at compile times: attribute parameters and enum definitions, and those rare times when you mean to define a value that does not change from release to release. For everything else, prefer the increased flexibility of readonly constants.
- Effective C#阅读笔记-2.使用readonly而不是const变量
- Prefer readonly to const - Effective C#学习笔记(2)
- Effective C# 原则2:为你的常量选择readonly而不是const(译)
- Effective C# 原则2:为你的常量选择readonly而不是const
- Effective C# 原则2:为你的常量选择readonly而不是const
- Effective C#读书笔记(2)Readonly优于Const
- Effective C# 2:Prefer readonly to const
- 创建常量时尽可能使用readonly,而不是const
- 规则二 对常量使用ReadOnly而不是const
- 【心得】在C#中使用静态变量const和动态变量readonly的区别
- c# const const readonly
- C# const, readonly, static readonly
- C# const, readonly, static readonly
- C# const, readonly, static readonly
- Effective C# 原则12:选择变量初始化而不是赋值语句
- c# readonly const 区别
- c# readonly vs const
- C# const.static.readonly.
- [ZOJ1462][POJ1112] Team Them Up!
- 用 CSS 实现 Firefox 和 IE 都支持的 Alpha 透明效果
- mod_wsgi与apache安装配置
- CListCtrl
- gitweb搭建
- Effective C#阅读笔记-2.使用readonly而不是const变量
- 想要申请PhD,真是路漫漫啊
- Memcached安装以及PHP的调用
- 构建后缀树的Ukkonen算法及其实现
- python连接mysql
- WinSocket编程详解
- VC用ADO访问数据库全攻略
- 获得系统时间
- Android Fragment学习笔记(二)