马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

C#各种字段类型对比

[复制链接]
查看1902 | 回复0 | 2019-9-17 11:30:51 | 显示全部楼层 |阅读模式

一、常量、只读字段、静态字段和静态只读字段对比

  1. 1 public class ModelClass
  2. 2 {
  3. 3 //常量在定义时必须赋初始值
  4. 4 //public const string constField;
  5. 5 public const string constField = "常量";
  6. 6 public readonly string readField = "只读字段";
  7. 7 public static string staticField = "静态字段";
  8. 8 public static readonly string staticReadField = "静态只读字段";
  9. 9
  10. 10 public ModelClass()
  11. 11 {
  12. 12 //常量的值在编译时就必须知道,而构造函数在运行时才执行,所以常量不能通过构造函数赋初值;而只读字段的值可以在运行时才决定。
  13. 13 //constField = "不能在构造函数中初始化常量";
  14. 14 readField = "构造函数初始化只读字段";
  15. 15 }
  16. 16 static ModelClass()
  17. 17 {
  18. 18 //constField = "不能在静态构造函数中初始化常量";
  19. 19 staticField = "静态构造函数初始化静态字段";
  20. 20 staticReadField = "静态构造函数初始化静态只读字段";
  21. 21 }
  22. 22
  23. 23 public string Method()
  24. 24 {
  25. 25 //在方法中定义常量并使用
  26. 26 const string constLocal = "局部常量";
  27. 27 string result = constLocal;
  28. 28 return result;
  29. 29 //readonly和static都不能在方法中使用
  30. 30 }
  31. 31 public static string StaticMethod()
  32. 32 {
  33. 33 //在静态方法中定义常量并使用
  34. 34 const string constLocal = "局部常量";
  35. 35 string result = constLocal;
  36. 36 return result;
  37. 37 //readonly和static都不能在静态方法中使用
  38. 38 }
  39. 39 }
  40. 40 public class RealizeObject
  41. 41 {
  42. 42 public void Realize()
  43. 43 {
  44. 44 //常量、静态字段和静态只读字段是类级别的
  45. 45 string value1 = ModelClass.constField;
  46. 46 string value2 = ModelClass.staticField;
  47. 47 string value3 = ModelClass.staticReadField;
  48. 48 //只读字段是对象级别的
  49. 49 ModelClass model = new ModelClass();
  50. 50 string value4 = model.readField;
  51. 51 //常量、只读字段和静态只读字段的值不能被修改
  52. 52 //ModelClass.constField = "不可以修改常量的值";
  53. 53 //model.readField = "不可以修改只读字段的值";
  54. 54 //ModelClass.staticReadField = "不可以修改静态只读字段的值";
  55. 55 ModelClass.staticField = "可以修改静态字段的值";
  56. 56 }
  57. 57 }
复制代码

常量、只读字段、静态字段和静态只读字段对比表:

113404zi9ug94gj1g9i924.png

常量、只读字段、静态字段和静态只读字段实用数据:

1、常量实用于定义时就已知且不能改变的数据。

2、只读字段实用于通过第三方在运行时赋值且不能改变的数据(对象独享)。

3、静态只读字段实用于通过第三方在运行时赋值且不能改变的数据(对象共享)。

4、静态字段实用于对象共享的数据。







来源:https://www.cnblogs.com/yaojieyuan/archive/2019/09/15/11508420.html
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则