C#-結構與枚舉

來源:互聯網
上載者:User
C#-結構與枚舉

1.類和結構的區別
1.1 不同點:  
     類型:類是參考型別,結構是實值型別.
     繼承:類可繼承,結構不能繼承.結構不能繼承其他的結構和類,或是被用作其他結構或類的基類.
     構造方法與析夠函數:結構可以定義構造方法,但不能定義析夠函數.類既可以定義構造方法,也可定義析夠函數.
1.2相同點
     對象建立:可以使用new進行初始化,或進行手工初始化.類和結構都可以.
     結構與介面:結構可以實現一個或多個介面. 如上:public struct BookComponent:IBook{  //....}.
     多態: 結構與介面之間是支援多態的.如上面的結構實現介面為例,多態:IBook book = new BookComponent();

2.枚舉
2.1
public enum Season
{
    SPRING,   //春天
    SUMMER,   //夏天
    AUTUMN,   //秋天
    WINTER    //冬天
}

public enum SeasonTwo
{
   SPRING = 0,   //春天
    SUMMER = 1,   //夏天
    AUTUMN = 2,   //秋天
    WINTER = 3    //冬天
}

用到時Console.WriteLine(Season.AUTUMN);    
            Console.WriteLine(SeasonTwo.AUTUMN);  

 FontStyle BtnFont = ( FontStyle)(Enum.Parse(typeof(FontStyle),“Bold”));
 
 簡單文字編輯器private void SetStyle(object sender,EventArgs e)
{           
    ToolStripButton btn = sender as ToolStripButton;
    FontStyle fontStyleContent = this.rchTxtContent.SelectionFont.Style;
    FontStyle BtnFont = ( FontStyle)(Enum.Parse(typeof(FontStyle),btn.Tag.ToString()));
    if ((fontStyleContent | BtnFont) == fontStyleContent)
   {
       fontStyleContent = ~BtnFont & fontStyleContent;
   }
    else
    {
        fontStyleContent = fontStyleContent | BtnFont;
   }
    this.rchTxtContent.SelectionFont = new Font(this.rchTxtContent.SelectionFont.FontFamily,
                                                this.rchTxtContent.SelectionFont.Size,
                                                fontStyleContent,
                                                this.rchTxtContent.SelectionFont.Unit);
}

2.2對象的形式實現
何為對象的形式實現呢? 其實這個很簡單,也就是將需要枚舉的標識定義在對象裡,通過對象的特性將其封裝.詳細如下代碼public class SeasonOne
{
    public static readonly SeasonOne SPRING = new SeasonOne("春天");
    public static readonly SeasonOne SUMMER = new SeasonOne("夏天");
    public static readonly SeasonOne AUTUMN = new SeasonOne("秋天");
    public static readonly SeasonOne WINTER = new SeasonOne("冬天");

   public SeasonOne(string name)
    {
        this.name = name;
    }

    //成員
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

用到時 Console.WriteLine(SeasonOne.AUTUMN.Name);

3.java中枚舉的進階用法(略,見下連結)
來自:http://www.cnblogs.com/beniao/archive/2008/07/27/1249029.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.