C#类和结构的区别

亦凉 2022-05-16 10:16 280阅读 0赞

类(class)和结构(struct)看起来功能差不多,但是内部还是有一些不同。

  1. 结构类型是值类型,类类型是引用类型。
  2. 凡是定义为结构的,都可以用类定义。
  3. 有些情况使用结构比使用类的执行效率高。

举例来说,我们现在需要十个点的坐标,在调用时需要初始化,现在来看一看两者都是怎么初始化的。

  1. //----------------ClassPoint.cs------------------
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace ClassStructExample
  8. {
  9. class ClassPoint
  10. {
  11. public int x, y;
  12. public ClassPoint(int x,int y)
  13. {
  14. this.x = x;
  15. this.y = y;
  16. }
  17. }
  18. }
  19. //----------------StructPoint.cs------------------
  20. using System;
  21. using System.Collections.Generic;
  22. using System.Linq;
  23. using System.Text;
  24. using System.Threading.Tasks;
  25. namespace ClassStructExample
  26. {
  27. struct StructPoint
  28. {
  29. public int x, y;
  30. public StructPoint(int x, int y)
  31. {
  32. this.x = x;
  33. this.y = y;
  34. }
  35. }
  36. }
  37. //----------------Program.cs------------------
  38. using System;
  39. using System.Collections.Generic;
  40. using System.Linq;
  41. using System.Text;
  42. using System.Threading.Tasks;
  43. namespace ClassStructExample
  44. {
  45. class Program
  46. {
  47. static void Main(string[] args)
  48. {
  49. ClassPoint[] p = new ClassPoint[10];
  50. for (int i = 0; i < p.Length; i++)
  51. {
  52. //必须为每个元素创建一个对象
  53. p[i] = new ClassPoint(i,i);
  54. Console.Write("({0},{1})",p[i].x,p[i].y);
  55. }
  56. Console.WriteLine();
  57. StructPoint[] sp = new StructPoint[10];
  58. for (int i = 0; i < sp.Length; i++)
  59. {
  60. //sp[i] = new StructPoint(i, i);
  61. //不用为每个元素创建一个对象,当然也可以创建,如上一行代码
  62. Console.Write("({0},{1})", sp[i].x, sp[i].y);
  63. }
  64. Console.WriteLine();
  65. }
  66. }
  67. }

输出结果:

70

在这个程序中,创建并初始化了一个含有10个点的数组。对于作为类实现的Point,出现了11个实例对象,包括声明数组的一个对象p,10个数组元素每个都要创建一个对象。而用结构实现Point,只需要创建一个对象。

如果数组是1000*1000,那么两者的程序执行效率会很不同。

发表评论

表情:
评论列表 (有 0 条评论,280人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C#结构区别

    类(class)和结构(struct)看起来功能差不多,但是内部还是有一些不同。 1. 结构类型是值类型,类类型是引用类型。 2. 凡是定义为结构的,都可以用类定义。

    相关 结构区别

    类 vs 结构 类和结构有以下几个基本的不同点: 类是引用类型,结构是值类型。 结构不支持继承。 结构不能声明默认的构造函数。 针对上述讨论,让我们重写前面的实例: