首页 > 其他分享 >接口实现和虚方法重写

接口实现和虚方法重写

时间:2022-09-07 11:14:25浏览次数:48  
标签:Console 重写 void 接口 Person Build WriteLine 方法 public

继承接口和继承基类的实例如下

public class Animal
{
    public virtual void Eat()
    {
        Console.WriteLine("Animal is eating!");
    }
}
public class Lion{}
public class Bird:Animal
{
    public override void Eat()
    {
        Console.WriteLine("Bird is eating!");
    }
    public virtual void Build()
    {
        Console.WriteLine("Bird is building nest!");
    }
}
public class Person:Animal
{
    public override void Eat()
    {
        Console.WriteLine("Person is eating!");
    }
    public virtual void Build()
    {
        Console.WriteLine("Person is building house!");
    }
}
public class Chinese:Person
{
    public override void Eat()
    {
        Console.WriteLine("Chinese is eating!");
    }
    public override void Build()
    {
        Console.WriteLine("Chinese is building the Great Wall!");
    }
}

 基类Animal有一个Eat虚方法,子类Person重写Eat,子类Lion不做任何操作,Person调用的是重写后的Eat,Lion则调用基类的Eat;在Person和Bird中又分别定义了Build虚方法,在每一个类中分别去定义Build显然是不合理的(但是有人觉得没毛病,哈哈哈哈),此时可以将Build抽出来放到接口中,Person和Bird实现该接口,修改代码如下

public class Bird:Animal,IAction
{
    public override void Eat()
    {
        Console.WriteLine("Bird is eating!");
    }
    public void Build()
    {
        Console.WriteLine("Bird is building nest!");
    }
}
public class Person:Animal,IAction
{
    public override void Eat()
    {
        Console.WriteLine("Person is eating!");
    }
    public void Build()
    {
        Console.WriteLine("Person is building house!");
    }
}
public class Chinese:Person
{
    public override void Eat()
    {
        Console.WriteLine("Chinese is eating!");
    }
}
public interface IAction
{
    public void Build();
}

那么问题就来了,实现接口中的Build和重写基类中的Build的区别是什么呢?当然不是指代码量上的区别

对比Eat和Build,可以看到Person的基类Chinese仍然可以重写Eat方法,而不能显示实现接口IAction中的Build方法,此时子类Chinese中使用的Build是其基类Person中实现的Build,那么如何在子类Chinese中实现对Build方法的“重写”?此时就要使用new关键字了,之前一直没想到new隐藏方法的使用场景是什么。。。修改代码如下

public class Chinese:Person
{
    public override void Eat()
    {
        Console.WriteLine("Chinese is eating!");
    }
    public new void Build()
    {
        Console.WriteLine("Chinese is building the Great Wall!");
    }
}

此时子类Chinese中的new表示隐藏了其基类Person中的Build方法,也可以在Person类中将实现的接口方法声明为Virtual,这样Chinese类中也可以直接对Build方法进行重写,代码如下

public class Person:Animal,IAction
{
    public override void Eat()
    {
        Console.WriteLine("Person is eating!");
    }
    public virtual void Build()
    {
        Console.WriteLine("Person is building house!");
    }
}
public class Chinese:Person
{
    public override void Eat()
    {
        Console.WriteLine("Chinese is eating!");
    }
    public override void Build()
    {
        Console.WriteLine("Chinese is building the Great Wall!");
    }
}
public interface IAction
{
    public void Build();
}

标签:Console,重写,void,接口,Person,Build,WriteLine,方法,public
From: https://www.cnblogs.com/celestially98/p/16664636.html

相关文章