C#学习笔记之——枚举、结构体
一、枚举
枚举类的赋值,值跟前一个的值有关,前一个值加一
例子:
enum Season: byte{
Spring=1,Summer,Fall,Winter
}
enum week{
MON=0,TUE=1,WED,THU,FRI,SAT,SUN
}
使用:
Season color = Season.Spring;
Console.WriteLine (color);
int n = Console.ReadLine () - 48;
switch ((week)n) {
case week.SUN:
Console.WriteLine ("have fun");
break;
case week.MON:
Console.WriteLine ("work");
break;
case week.TUE:
Console.WriteLine ("work");
break;
case week.WED:
Console.WriteLine ("work");
break;
case week.THU:
Console.WriteLine ("work");
break;
case week.FRI:
Console.WriteLine ("work");
break;
case week.SAT:
Console.WriteLine ("have fun");
}
二、结构体
结构体的字段不能赋初值
结构体构造方法必须给每个字段赋初值
有五个学生,用结构体存储姓名、学号、年龄、分数;
1、找出最高分的学生,并输出他的信息
2、按照年龄从小到大排序,并输出
using System;
namespace Lesson11
{
public struct Person
{
public string name;
public int age;
public string studentID;
public int score;
}
enum Gender {
male,female
}
class MainClass
{
public static void Main (string[] args){
Person[] persons = new Person[5];
persons[1].name = "Araina";
persons[1].studentID = "01";
persons[1].age = 20;
persons[1].score = 98;
persons[0].name = "Michael";
persons [0].studentID = "02";
persons[0].age = 22;
persons [0].score = 95;
persons[2].name = "Selena";
persons [2].studentID = "03";
persons[2].age = 18;
persons [2].score = 100;
persons[3].name = "Ed";
persons [3].studentID = "04";
persons[3].age = 25;
persons [3].score = 99;
persons[4].name = "P!nk";
persons [4].studentID = "05";
persons[4].age = 27;
persons [4].score = 94;
string personWhoGetHighScore = persons[0].name;
int highScore = persons[0].score;
int i = 1;
for ( ; i < 5; i++) {
if(persons[i].score > highScore){
highScore = persons [i].score;
personWhoGetHighScore = persons [i].name;
}
}
int theOne = 0;
for ( ; i < 5; i++) {
if(persons[i].score == highScore){
theOne = i;
}
}
Console.WriteLine ("分数最高的是:" + personWhoGetHighScore);
Console.WriteLine ("年龄:" + persons [theOne].age);
Console.WriteLine ("学号:" + persons [theOne].studentID);
Console.WriteLine ("分数:" + highScore);
Person temp;
for (i = 0; i < persons.Length-1; i++) {
for (int j = 0; j < persons.Length-(i+1); j++) {
if(persons[j].age > persons[j+1].age)
{
temp = persons [j];
persons [j] = persons [j + 1];
persons [j + 1] = temp;
}
}
}
foreach (Person one in persons) {
Console.WriteLine ("name:{0} age:{1}", one.name, one.age);
}
}
}
}