接口(一)

示例代码:

using System;
public interface IAnimal
{
    void Walk();
}

public class Cat : IAnimal
{
    public void Walk()
    {
        Console.WriteLine("Cat is walking");
    }
}

public sealed class Program
{
    public static void Main()
    {
        // type of cat is Cat, call Cat's Walk method
        Cat cat = new Cat();
        cat.Walk();

        // type of animal is IAnimal, call IAnimal's Walk
        IAnimal animal = (IAnimal) cat;
        animal.Walk();
    }
}

实现接口方法时,若没有显式加virtual 关键字修饰,则编译器自动添加关键字virtualsealed 修饰。若显式添加了virtual 关键字,则其派生类可以重写该方法。

以上示例中,需要明确,Cat类中实现的Walk方法既是自己的一个公共方法,也是实现IAnimal接口的方法。作为其自有的公共方法,这允许以下代码调用该方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值