004 C# 结构体Struct
C# 结构体(Struct)
在 C# 中,结构体是值类型数据结构。它使得一个单一变量可以存储各种数据类型的相关数据。struct 关键字用于创建结构体。
例:
struct Books { public string title; public string author; public string subject; public int book_id; }; Books Book1; /* 声明 Book1,类型为 Books */ Books Book2; /* 声明 Book2,类型为 Books */ /* book 1 详述 */ Book1.title = "C Programming"; Book1.author = "Nuha Ali"; Book1.subject = "C Programming Tutorial"; Book1.book_id = 6495407; /* book 2 详述 */ Book2.title = "Telecom Billing"; Book2.author = "Zara Ali"; Book2.subject = "Telecom Billing Tutorial"; Book2.book_id = 6495700;
Notes:
1. C#的结构体,不支持以整个对象形式来赋值(初始化)。而必须对每一项结构体属性单独赋值。
2. 但是,可以通过“构造函数”来初始化结构体变量的值。但是需要对所有变量都赋值(不能有遗漏)。
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; struct Person { public string name; public int age; public Day workingday; public Person(string name, int age) { this.name = name; // 赋值name this.age = age; // 赋值age this.workingday = Day.Mon; //赋值workingday } public void PrintInfo() { Console.WriteLine("Name: {0}\nAge: {1}\nWorkingday: {2}", this.name, this.age, this.workingday); }
};
3. 在使用new来生成一个结构体实例时,会自动调用“构造方法”
Person p1 = new Person("haha", 36); p1.PrintInfo();
输出:
Name: haha
Age: 36
Workingday: Mon
4. 结构体,可以有常量const和静态static字段
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; struct Person { public string name; public int age; public Day workingday; const int holidays = 10; // 常量“holidays” public static int count = 0; // 静态属性“count” public Person(string name, int age) { this.name = name; this.age = age; this.workingday = Day.Mon; Person.count++; } public void PrintInfo() { Console.WriteLine("Name: {0}\nAge: {1}\nWorkingday: {2}\nholidays: {3}", this.name, this.age, this.workingday, holidays); // 这里调用常量,不需要加this. } }; Console.WriteLine("生成的人数: {0}", Person.count);

浙公网安备 33010602011771号