枚舉和結構體
枚舉格式: enum 枚舉類型 { 符號1,符號2....} 預設情況下編號從0開始,他代表第一個元素,以後每個元素編號遞增1,可以重寫這個賦值的過程
enum 枚舉類型{符號1=1,符號2=2,。。。。}
聲明一個枚舉類型時,枚舉直接量將獲得intleixign的值即基礎類型預設的時int,但是亦可以使枚舉類型基於一種不同的基礎資料類型(byte,sbyte,
int,uint,long,ulong)eg: enum season:short{spring,summer,fall,winter}
using System;
using System.Collections.Generic;
using System.Text;
namespace four
{
enum week { sunday, moday, tuesday, wednesday, thursday, friday, saturday };
class Program
{
static void Main(string[] args)
{
week day = week.friday;
byte fistChar = (byte)day;//獲得day所在位置
Console.WriteLine(day+" "+fistChar);
Console.ReadLine();
}
}
}
結構 : 由許多資料群組成的資料結構,它是在堆棧上儲存的,可以有效減少記憶體的管理開銷
結構中的資料由各種類型,結構可以包含自己的欄位,方法和建構函式,結構和類幾乎完全相同,區別在於結構是實值型別,類是參考型別
問題 結構 類
是實值型別還是參考型別 指類型 參考型別
其執行個體存在堆還是棧上 其執行個體叫值位於棧上 其執行個體叫為對象位於堆上
能否聲明預設的建構函式 否 能
如果聲明自己的建構函式 會 不會
編譯器是否仍會產生默
認的建構函式
在自己的建構函式中不初 不會 會
始化一個欄位,編譯器是
否會協助初始化
是否可以在聲明一個執行個體字 否 是
段的同時執行個體化它
格式:struct 結構名稱{
<存取修飾詞> 類型 名稱;
}
using System;
using System.Collections.Generic;
using System.Text;
namespace four
{
struct Round { //聲明一個結構體Round
public double r;//半徑
public Round(double x) {//建構函式,初始化半徑
r = x;
}
public double Area() {
return Math.PI * r * r;
}
}
class Program
{
static void Main(string[] args)
{
Round ro;
ro.r = 3;
Console.WriteLine("第一個圓的面積:{0}",ro.Area());
Console.ReadLine();
}
}
}