类的赋值
在C#中我们可以将一种类型的对象赋值给继承层次结构中较高位置的一个类的变量,粗俗点就是我们的子类能够赋值给他的父类,好比所有的狗它们都属于动物这一类,所以动物是最高层的但是要注意,如果我们将子类对象变量赋值给父类对象,我们是不可以调用其子类的方法和字段,只能访问父类的方法和字段。例如
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpTest
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();//实例化对象Dog类
Cat cat = new Cat();//实例化对象Cat类
Animal animal = dog;//所有的狗都是动物,动物为高位置变量
}
}
}
我们看看animal中有什么方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpTest
{
class Animal
{
public int leg;
public int eye;
public Animal()
{
leg = 4;
eye = 2;
Console.WriteLine("调用父类构造方法");
}
public void Breathe()
{
Console.WriteLine("我在呼吸");
}
public void Sleep()
{
Console.WriteLine("我在睡觉");
}
}
}
我们看看dog中有什么方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpTest
{
class Dog:Animal
{
public Dog()
:base()
{
Console.WriteLine("子类构造方法:我是一只小狗");
}
public void eat()
{
Console.WriteLine("我爱吃骨头");
}
}
}
我们利用animal对象试试看能调用什么方法
可以发现里面并没有eat方法,这正好说明了我们将dog赋值给animal但我们不能去访问dog的方法和字段,因为所有的狗都是动物,但不是所有的动物都是狗,它有可能是猫,老鼠,鲨鱼等等,如果我们必须得调用其赋值对象的方法,那么我们可以使用强制类型转换,在调用前加个(Dog)。