结构体和类的区别
C#中的每一种类型要么是值类型,要么是引用类型,所以每个对象要么是值类型的实例,要么是引用类型的实例。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class structtest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { TestStruct T1,T2; //与类一样,但可以不new T1.Name = "TestStruct"; T2 = T1; //将T1的值赋给T2 //由于是值类型,因此赋值等于将全部值全部复制到T2的栈空间 T2.Name = "TestStruct1"; //然后修改T2的值看是否改变T1 Label1.Text = T1.Name; //输出 TestStruct,没被改变 Test T3 = new Test(); T3.Name = "Test"; Test T4 = new Test(); T4 = T3; //将T3的值赋给T4 赋值后,由于是引用类型,因此两个对象指向的是同一个地址(堆空间) T4.Name = "Test1"; //然后修改T4的值看是否改变T3 Label2.Text = T3.Name; //输出 Test1,被改变 } } public class Test { public string Name; } public struct TestStruct { public string Name; }