這篇文章將為大家詳細講解有關C#中如何定義結構體,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
站在用戶的角度思考問題,與客戶深入溝通,找到魚臺網站設計與魚臺網站推廣的解決方案,憑借多年的經驗,讓設計與互聯網技術結合,創造個性化、用戶體驗好的作品,建站類型包括:成都網站建設、成都做網站、企業官網、英文網站、手機端網站、網站推廣、主機域名、虛擬主機、企業郵箱。業務覆蓋魚臺地區。
C#結構體定義的情況:
C#結構體定義也可以象類一樣可以單獨定義.
class a{}; struct a{};
C#結構體定義也可以在名字前面加入控制訪問符.
public struct student{}; internal struct student{};
如果結構體student沒有publice或者internal的聲明 類program就無法使用student結構定義 obj對象
如果結構體student的元素沒有public的聲明,對象obj就無法調用元素x
因為默認的結構體名和元素名是private類型
C#結構體定義之程序:
using System; public struct student { public int x; }; class program { public static void Main() { student obj=new student(); obj.x=100; } };
在結構體中也可以定義靜態成員與類中一樣,使用時必須用類名,或結構名來調用不屬于實例,聲明時直接定義.
C#結構體定義程序:
using System; public struct student { public static int a = 10; }; class exe { public static void Main() { Console.WriteLine( student.a = 100); } };
或
using System; class base { public struct student { public static int a = 10; }; } class exe { public static void Main() { Console.WriteLine( base.student.a = 100); } };
在結構體中可以定義構造函數以初始化成員,但不可以重寫默認無參構造函數和默認無參析構函數
C#結構體定義程序:
public struct student { public int x; public int y; public static int z; public student(int a,int b,int c) { x=a; y=b; student.z=c; } };
在結構體中可以定義成員函數。
C#結構體定義程序:
public struct student { public void list() { Console.WriteLine("這是構造的函數"); } };
結構體的對象使用new運算符創建(obj)也可以直接創建單個元素賦值(obj2)這是與類不同的因為類只能使用new創建對象
C#結構體定義程序:
public struct student { public int x; public int y; public static int z; public student(int a,int b,int c) { x=a; y=b; student.z=c; } }; class program { public static void Main() { student obj=new student(100,200,300); student obj2; obj2.x=100; obj2.y=200; student.z=300; } }
在使用類對象和函數使用時,使用的是引用傳遞,所以字段改變
在使用結構對象和函數使用時,是用的是值傳遞,所以字段沒有改變
C#結構體定義程序:
using System; class class_wsy { public int x; } struct struct_wsy { public int x; } class program { public static void class_t(class_wsy obj) { obj.x = 90; } public static void struct_t(struct_wsy obj) { obj.x = 90; } public static void Main() { class_wsy obj_1 = new class_wsy(); struct_wsy obj_2 = new struct_wsy(); obj_1.x = 100; obj_2.x = 100; class_t(obj_1); struct_t(obj_2); Console.WriteLine("class_wsy obj_1.x={0}",obj_1.x); Console.WriteLine("struct_wsy obj_2.x={0}",obj_2.x); Console.Read(); } }
C#結構體定義程序運行結果為:
class_wsy obj_1.x=90 struct_wsy obj_2.x=100
關于C#中如何定義結構體就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
新聞標題:C#中如何定義結構體
文章路徑:http://vcdvsql.cn/article30/jhihpo.html
成都網站建設公司_創新互聯,為您提供定制網站、全網營銷推廣、、面包屑導航、品牌網站建設、網站導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯