最近看鹏哥的教程和《C#入门经典》都有了些困难,就是题目这个。using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;public class Animal
{
public string word="";
public virtual void Introduce()
{word="I am an animal";}
}
public class Dog:Animal
{
public override void Introduce()
{word="I am an Dog";}
public class Cat:Animal
{
public new void Introduce()
{word="I am an Dog";
}
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Animal theAnimal =new Dog();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word); Dog theAnimal =new Dog ();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word); Animal theAnimal=new Cat();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word); Cat theAnimal=new Cat();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word);
Console.ReadKey();
}
}
}我想问:(1)为什么这4个例子执行结果不同?
(2)创建实例的时候最左边那个是类型?这个类的类型是怎样的(感觉int,float啊这样的类型比较直观,自己创建的类型就想象不出来了)
(3)类的类型转换是怎么回事?我这样做行不行?int a=100;
int b;
Animal c;
b=(Animal)a;
c=(Animal)a;谢谢您的点拨!
using System.Collections.Generic;
using System.Linq;
using System.Text;public class Animal
{
public string word="";
public virtual void Introduce()
{word="I am an animal";}
}
public class Dog:Animal
{
public override void Introduce()
{word="I am an Dog";}
public class Cat:Animal
{
public new void Introduce()
{word="I am an Dog";
}
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Animal theAnimal =new Dog();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word); Dog theAnimal =new Dog ();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word); Animal theAnimal=new Cat();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word); Cat theAnimal=new Cat();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word);
Console.ReadKey();
}
}
}我想问:(1)为什么这4个例子执行结果不同?
(2)创建实例的时候最左边那个是类型?这个类的类型是怎样的(感觉int,float啊这样的类型比较直观,自己创建的类型就想象不出来了)
(3)类的类型转换是怎么回事?我这样做行不行?int a=100;
int b;
Animal c;
b=(Animal)a;
c=(Animal)a;谢谢您的点拨!
c=(Animal)a;是强制转换成Animal型.最左边的是个类.
2.实例化时,左边类型一定是右边同类型或者右边类型的父类,才能实例化成功。因为子类继承父类的特性,但是父类并不拥有子类的特性。
举个例子,当你家有只动物时,你可以告诉朋友它是狗也可以说他是猫。也就是当你声明类型为动物时,实例化时动物可以是狗,也可以是猫。但是当你有家狗时,你实例化事就不能说是动物,因为并不是所有的动物都会"汪汪"
3.根据上面的规则,你这个转换不能成功,你想想,int型,怎么能拥有Animal类的特性?
theAnimal.Introduce();//Dog类的Introduce重写了父类的方法
Console.WriteLine(theAnimal.word);//打映:I am an Dog I am an Animal Dog theAnimal =new Dog ();
theAnimal.Introduce();
Console.WriteLine(theAnimal.word);打映:I am an Dog
int a=100;//int是值类型
int b;
Animal c;//Animal是引用类型
b=(Animal)a;//着样转换,好向不行
c=(Animal)a;
(Animal)a=(object)a;
装箱一次
{
public string word="";
public virtual void Introduce() //隐式虚方法
{word="I am an animal";}
}
public class Dog:Animal //Dog类继承了Animal类
{
public override void Introduce()//重写父类的方法
{word="I am an Dog";}
public class Cat:Animal //Cat类继承Animal类
{
public new void Introduce()
{word="I am an Dog";
}
不妨把鼠标移到int上面停一秒钟,OK,看看INT到底是什么
yes
就是他了
嚯嚯原来你每天用的Int也是class啊哈哈哈