C#结构体特性实例分析

2019-12-26 13:31:46王冬梅

在使用类对象和函数使用时,使用的是引用传递,所以字段改变

在使用结构对象和函数使用时,是用的是值传递,所以字段没有改变

程序:

 

 
  1. using System;  class class_wsy 
  2. {  public int x; 
  3. }  struct struct_wsy 
  4. {  public int x; 
  5. }  class program 
  6. {  public static void class_t(class_wsy obj) 
  7. {  obj.x = 90; 
  8. }  public static void struct_t(struct_wsy obj) 
  9. {  obj.x = 90; 
  10. }  public static void Main() 
  11. {  class_wsy obj_1 = new class_wsy(); 
  12. struct_wsy obj_2 = new struct_wsy();  obj_1.x = 100; 
  13. obj_2.x = 100;  class_t(obj_1); 
  14. struct_t(obj_2);  Console.WriteLine("class_wsy obj_1.x={0}",obj_1.x); 
  15. Console.WriteLine("struct_wsy obj_2.x={0}",obj_2.x);  Console.Read(); 
  16. }  } 

结果为:

 

 
  1. class_wsy obj_1.x=90  struct_wsy obj_2.x=100