1. 程式人生 > >列舉和結構體的區別

列舉和結構體的區別

列舉型別:

enum Position

{

x,

y,

z

}

static void Main(String[ ] args)

{

Position pos = Position.x; // x為Position裡的屬性

Console.WriteLine(pos);

int num = (int) pos;//顯示轉換

Console.WriteLine(num); //結果為0

}

列舉型別預設為是int型別,並預設為從0,1,2,3...遞增排序,也可為屬性賦值,也可改變列舉型別的int型別(如將其換成byte來減少記憶體的消耗)如:

enum Position:byte

{

x = 100,

y = 200,

z = 134

}


結構體:

stuct Student

{

public String name;

public String school;

}

static void Main(String[ ] args)

{

Student tom;

tom.name = "Tom";

tom.school = "ZK";

Console.WriteLine(tom.name + tom.school);

}

結構體可以將有限個不同型別的屬性變數組合在一起,與列舉型別不同之處是列舉型別內的都是同類型的屬性變數,並且結構體可以有結構函式。如:

stuct Student

{

public String name;

public String school;

        public String info(int time)

{

return name +" "+ school + time;

}

}

static void Main(String[ ] args)

{

Student tom;

tom.name = "Tom";

tom.school = "ZK";

int mytime = 10;

Console.WriteLine(tom.info(mytime));

}