C#.NET中的类的实例的类型转换
/*
* 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 ();
}
}
* 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 ();
}
}
运行结果如下: