先定义一个接口,以及实现该接口的几个阿猫阿狗
interface IAnimal
{
string NickName
{
get;
set;
}
void Eat();
void Sleep();
}
public class Dog : IAnimal
{
public string NickName
{
get;
set;
}
public void Eat()
{
Console.WriteLine("Dog eat");
}
public void Sleep()
{
Console.WriteLine("Dog Sleep");
}
}
public class Cat : IAnimal
{
string IAnimal.NickName
{
get;
set;
}
void IAnimal.Eat()
{
Console.WriteLine("Cat eat");
}
void IAnimal.Sleep()
{
Console.WriteLine("cat sleep");
}
}
public class BigWolfDog : Dog, IAnimal
{
}
public class SmallWolfDog : Dog
{
}
public class Duck
{
public string NickName
{
get;
set;
}
public void Eat()
{
Console.WriteLine("a duck can eat");
}
public void Sleep()
{
Console.WriteLine("a sleeping duck");
}
}
public class YellowDuck:Duck,IAnimal
{
}
然后去main里new 对象:
IAnimal cat = new Cat();
cat.Eat();
IAnimal dog = new Dog();
dog.Sleep();
IAnimal bigWolfDog = new BigWolfDog();
bigWolfDog.Eat();
IAnimal smallWolfDog = new SmallWolfDog();
smallWolfDog.Sleep();
SmallWolfDog swd = new SmallWolfDog();
swd.Eat();
IAnimal yellowDuck = new YellowDuck();
yellowDuck.Sleep();
然后发现:
1,只要实现了接口IAnimal,就可以IAnimal obj = new Dog/Cat(),无论是隐式继承还是显式继承;
2,实现了接口IAnimal的Dog的子类实例化的时候,可以直接
SmallWolfDog swd = new SmallWolfDog();
或者IAnimal swd = new SmallWolfDog();
3,Duck本身跟接口IAnimal没有关系,但是Duck本身包含了接口的所有定义的属性、方法,此时小黄鸭
public class YellowDuck:Duck,IAnimal
继承了Duck、同时实现了IAnimal,则YellowDuck内部可以不去实现IAnimal的方法。