• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

EffectiveC#学习笔记(二)readonly和const的性能和灵活性的权衡

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

运行时和编译时的常量的声明

// Compile time constant:

public const int Millennium = 2000;

// Runtime constant:

public static readonly int ThisYear = 2004;

 

区别:

编译时常量只能用来声明原始类型变量 int double float string and so on

 

而运行时常量可以声明任何常量

 

好处:

在改变常量值的时候,用运行时常量声明的程序集 只需重新编译自己 而不需编译所有引用该程序集的应用程序就可改变程序集的版本,而编译时的常量则需编译所有的应用及相关程序集。

 

用编译时变量的场景,如:程序的版本控制

 


 1 private const int Version1_0 = 0x0100;
 2 
 3 private const int Version1_1 = 0x0101;
 4 
 5 private const int Version1_2 = 0x0102;
 6 
 7 // major release:
 8 
 9 private const int Version2_0 = 0x0200;
10 
11 // check for the current version:
12 
13 private static readonly int CurrentVersion =
14 
15 Version2_0;
16 
17 You use the runtime version to store the current version in each saved file:
18 
19 // Read from persistent storage, check
20 
21 // stored version against compile-time constant:
22 
23 protected MyType(SerializationInfo info,
24 
25 StreamingContext cntxt)
26 
27 {
28 
29   int storedVersion = info.GetInt32("VERSION");
30 
31   switch (storedVersion)
32 
33   {
34 
35     case Version2_0:
36 
37     readVersion2(info, cntxt);
38 
39     break;
40 
41   case Version1_1:
42 
43   readVersion1Dot1(info, cntxt);
44 
45   break;
46 
47   // etc.
48 
49   }
50 
51 }
52 
53 // Write the current version:
54 
55 [SecurityPermissionAttribute(SecurityAction.Demand,
56 
57 SerializationFormatter = true)]
58 
59 void ISerializable.GetObjectData(SerializationInfo inf,
60 
61 StreamingContext cxt)
62 
63 {
64 
65 // use runtime constant for current version:
66 
67 inf.AddValue("VERSION", CurrentVersion);
68 
69 // write remaining elements...
70 
71 }

 

总结:在属性参数和枚举参数中使用const ,其他情况请使用static readonly声明常量


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap