C#中的结构体(struct)

作者:追风剑情 发布于:2019-7-1 14:39 分类:C#

示例

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace StructTest
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Books book1 = new Books();
  13. Books book2;
  14.  
  15. book1.title = "title 1";
  16. book1.author = "author 1";
  17. book1.ID = 0;
  18. book1.onChangeTitle += OnChangeTitle;
  19.  
  20. //按值传递
  21. book2 = book1;
  22. book2.title = "title 2";
  23. book2.author = "author 2";
  24.  
  25. Console.WriteLine("book1.title=" + book1.title);
  26. Console.WriteLine("book1.author=" + book1.author);
  27.  
  28. Console.WriteLine("book2.title=" + book2.title);
  29. Console.WriteLine("book2.author=" + book2.author);
  30.  
  31. Console.ReadKey();
  32. }
  33.  
  34. private static void OnChangeTitle()
  35. {
  36.  
  37. }
  38.  
  39. interface IBook
  40. {
  41. string GetDescription();
  42. }
  43.  
  44. /**
  45. * 1. 结构中的字段无法赋初值
  46. * 2. 结构可带有方法、字段、索引、属性、运算符方法和事件
  47. * 3. 结构不能继承其他的结构或类
  48. * 4. 结构可实现一个或多个接口
  49. * 5. 结构成员不能指定为 abstract、virtual 或 protected
  50. * 6. 结构可以不使用new操作符即可被实例化(所有字段赋值后,对象才能被使用)
  51. * 7. 结构存储在栈中,类对象存储在堆中,结构适合描述轻量级对象
  52. * 8. 结构是按值传递,类对象是按引用传递
  53. */
  54. struct Books : IBook
  55. {
  56. public delegate void ChangeTitleEvent();
  57. public event ChangeTitleEvent onChangeTitle;
  58.  
  59. public string title;
  60. public string author;
  61. public int ID { set; get; }
  62.  
  63. // 可以定义有参结构函数
  64. public Books(string title)
  65. {
  66. //必须为所有字段赋上值
  67. this.title = title;
  68. this.author = "";
  69. this.ID = 0;
  70. this.onChangeTitle = null;
  71. }
  72.  
  73. // 不能定义析构函数
  74. //~Books() { }
  75.  
  76. public string GetDescription()
  77. {
  78. return string.Empty;
  79. }
  80.  
  81. public override string ToString()
  82. {
  83. return title + " " + author;
  84. }
  85.  
  86. public string this[int index]
  87. {
  88. get { return title; }
  89. set { title = value; }
  90. }
  91.  
  92. // 重载+运算符
  93. public static Books operator +(Books b, Books c)
  94. {
  95. Books book = new Books();
  96. book.title = b.title + c.title;
  97. book.author = b.author + c.author;
  98. return book;
  99. }
  100. }
  101. }
  102. }


运行测试
111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号