C#.NET中的類的執行個體的類型轉換

來源:互聯網
上載者:User
/*
 * Created by SharpDevelop.
 * User: noo
 * Date: 2009-8-17
 * Time: 11:27
 * 
 * 類的執行個體的類型轉換
 */

using System ;
class Fruit
{
    public virtual void Do()
    {
        Console.WriteLine ("水果類的Do方法");
    }
    public void DoSomething()
    {
        Console.WriteLine ("水果類的DoSomething方法");
    }
    public void DoSomethingElse()
    {
        Console.WriteLine ("水果類的DoSomethingElse方法");
    }
}
class Apple:Fruit
{
    public override void Do()//重寫
    {
        Console.WriteLine ("重寫水果類的Do方法");
    }
    new public void DoSomething()//隱藏
    {
        Console.WriteLine ("隱藏水果類的DoSomething方法");
    }
    public void OutPut()
    {
        Console.WriteLine ("蘋果類的OutPut方法");
    }
}
class Test
{
    static void Main()
    {
        Fruit f=new Apple ();//隱式轉換
        f.Do ();
        f.DoSomething ();
        f.DoSomethingElse ();
        
        Fruit ff=new Apple ();//隱式轉換,與下三句等價
//        Fruit ff=new Fruit ();
//        Apple a=new Apple ();
//        ff=aa;
        Apple aa=ff as Apple ;//顯式轉換,與下兩句等價
//        Apple aa=new Apple ();
//        aa=ff as Apple ;//或者aa=(Apple)ff;由於as運算子必須與參考型別一起使用,類時參考型別的,故可以寫作aa=ff as Apple;
        aa.Do ();
        aa.DoSomething ();
        aa.DoSomethingElse ();
        aa.OutPut ();
    }
}運行結果如下:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.