C#の構造体¶
構造体とは¶
「intやcharなどの基本データ型を好きなように組み合わせて、新しいデータ型として扱うもの」を「構造体」と呼びます。構造体はひとつの名前だけで関連したいくつもの変数を一度にあつかうことができます。通常それらの間には密接な関係があり、構造体はそれらをひとつの名のもとに組織化するという働きをします。structsとクラスの違いは、それはできませんは抽象的、継承の実現も支持できない。
単独で定義:
1 2 | class a { }; struct a { }; |
規制訪問符を持っている:
1 2 | public struct student { }; internal struct student { }; |
構造体の運用¶
もしstudent構造体はpublicやinternalの声明しないが、クラスProgramはstudentの構造定義obj対象が使用できません。 もしstudent構造体の要素はpublicの声明しないが 、対象objは元素Xが呼び出しない.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using System; public struct student { public int x; } class program { public static void Main() { student obj = new student(); obj.x = 100; } }; |
構造体の中でも定義静態メンバーとクラスのように、使用時でなければクラス名、または構造名に呼び出して
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using System; public struct Student { public static int A = 10; } class Exe { public static void Main() { Console.WriteLine(Student.A = 100); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | using System; class Base { public struct Student { public static int A = 10; } } class Exe { public static void Main() { Console.WriteLine(Base.Student.A = 100); } } |
構造体の中でコンストラクタの運用できる、黙認の参数を持っていないコンストラクタの複写は許可できない.
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } |
成員関数の定義:
1 2 3 4 5 6 7 | public struct Student { public void list() { Console.WriteLine("これは構造の関数"); } } |
構造体の対象はnew演算子を使用して作成obj1、も直接obj2作成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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; } } |
使用クラス対象と関数の使用時は、使用の引用伝えるので、フィールドを変える。使用構造対象と関数の使用時は、使ったのは値を伝えるので、フィールドを変わらない
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; class Class_Test { public int x; } struct Struct_Test { public int x; } class Program { public static void class_t(Class_Test obj) { obj.x = 90; } public static void struct_t(Struct_Test obj) { obj.x = 90; } public static void Main() { Class_Test obj_1 = new Class_Test(); Struct_Test obj_2 = new Struct_Test(); obj_1.x = 100; obj_2.x = 100; class_t(obj_1); struct_t(obj_2); Console.WriteLine("Class_Test obj_1.x={0}", obj_1.x); Console.WriteLine("Struct_Test obj_2.x={0}", obj_2.x); Console.Read(); } } |
運行结果: Class_Test obj_1.x=90 Struct_Test obj_2.x=100
by 王銀玉