在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
运行时和编译时的常量的声明 // 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声明常量 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论