结构类型:值类型,而类是引用类型
结构定义:
- 结构的定义方式与类非常类似,但结构是值类型,而类是引用类型;
- 对象是引用类型,在把对象赋给变量时,就把一个指针的变量赋给了该指针所指向的对象,改变其中的一个值,值也改变;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { class MyClass { public int val; } struct MyStruct { public int val; } static void Main(string [] args) { MyClass objectA = new MyClass(); MyClass objectB = objectA; objectA.val = 100; objectB.val = 200; MyStruct StructA = new MyStruct(); MyStruct StructB = StructA; StructA.val = 100; StructB.val = 200; Console.WriteLine("object A = {0}",objectA.val); Console.WriteLine("object B = {0}",objectB.val); Console.WriteLine("Struct A = {0}",StructA.val); Console.WriteLine("Struct B = {0}", StructB.val); Console.ReadLine(); } } }
结果:
object A =200
object B =200
Struct A =100
Struct B =200
时间: 2024-10-11 06:31:27