標籤:hstp osc cst ann tar xfs adf iic ora
1、struct 結構與class(類)的區別
1)struct是實值型別,class是物件類型
2)struct不能被繼承,class可以被繼承
3)struct預設存取權限是public,而class預設是private
5) struct不能由程式員申明建構函式,有編輯器自動產生,用於描述輕量級對象,執行效率高,例如:Line,Point等
6)struct的new和class的new是不同的,struct的new就是執行一下建構函式建立一個執行個體,再對所有欄位進行複製。
而class則是在堆上分配一塊記憶體再執行建構函式,struct記憶體並不是在new的時候分配的,而是是定義的時候分配。
7)struct 可以不用new來執行個體化,而類卻要,如果struct不用new來執行個體化,那麼結構的所有欄位處於未分配狀態。
2、驗證struct和class的區別
1)struct是否可被class繼承
/// <summary> /// 定義一個結構 /// </summary> struct WinPoint { public int Left; public int Right; } /// <summary> /// 定義一個類 /// </summary> class TestClass: WinPoint { public int Left; public int Right; }
這樣,TestClass類繼承結構是不行的,編譯時間報錯如下
2)struct是否可被struct繼承
/// <summary> /// 定義一個結構 /// </summary> public struct WinPoint { public int Left; public int Right; } /// <summary> /// 再定義一個結構 /// </summary> public struct WinPoint1: WinPoint { }
struct不能被另一個struct繼承,編譯時間報錯如下:
3)class是否可被class繼承
/// <summary> /// 定義一個父類 /// </summary> public class TestClass { public int Left; public int Right; } /// <summary> /// 定義一個子類,繼承父類屬性 /// </summary> public class TestClass1 : TestClass { }
在使用的時候,可以調用父類的屬性
public void TestClick(){ TestClass1 test1 = new TestClass1(); test1.Left = 10; test1.Right = 20; }
4)struct在方法傳遞是否是副本
類和結構的建立
/// <summary> /// 定義一個結構 /// </summary> public struct TheStruct { public int Left; public int Right; } /// <summary> /// 定義一個類 /// </summary> public class TheClass { public int Left; public int Right; } public class TestClass { /// <summary> ///賦值方法(結構) /// </summary> /// <param name="thestruct"></param> public static void StructTaker(TheStruct thestruct) { thestruct.Left = 20; thestruct.Right = 30; } /// <summary> /// 賦值方法(類) /// </summary> /// <param name="theclass"></param> public static void ClassTaker(TheClass theclass) { theclass.Left = 20; theclass.Right = 30; } }
調用的方法
private void btnTest_Click(object sender, EventArgs e) { //建立一個機構執行個體對象 TheStruct stu = new TheStruct(); //賦初始值 stu.Left = 1; //建立一個類執行個體對象 TheClass cla = new TheClass(); cla.Left = 1; //重新給機構和類賦值 TestClass.StructTaker(stu); //調用方法,重新設定為20 TestClass.ClassTaker(cla); //調用方法,重新設定為20 //輸出結構 MessageBox.Show("結構stu.Left:"+stu.Left+",類cla.Left:"+cla.Left); }
最後的彈出結果,如
剛開始都初始化為Left的值為1,重新賦值為20時,機構的Left沒有改變,類的Left改變了,這就證明當一個結構傳遞到一個方法時,被傳遞的只不過是一個副本,
而一個類被傳遞,被傳遞是一個引用對象地址。
參考網址:
http://www.cnblogs.com/tonytonglx/articles/2080470.html
.net 中struct(結構)和class(類)的區別