/*
* 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 ();
}
}運行結果如下: