C#基础知识之interface

本文探讨了C#编程中的接口概念,虽然作者最初对其作用感到困惑,但通过学习总结,解释了接口在软件设计中的重要性和使用场景,鼓励读者深入理解和应用。
摘要由CSDN通过智能技术生成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interface
{
    interface IRunable
    {
        float Distance
        {
            get;
        }
        float Speed
        {
            get;
            set;
        }
        void Run( );
    }

    interface IShoutable
    {
        void Shout( );
    }

    class Cow : IRunable, IShoutable
    {
        private float _Distance = 0.0f;
        //实现IRunable.Distance属性
        public float Distance
        {
            get 
            {
                return this._Distance;
            }
        }
        private float _Speed;
        //实现IRunable.Speed属性
        public float Speed
        {
            get
            {
                return this._Speed;
            }
            set
            {
                this._Speed = value;
            }
        }
        //实现IRunable.Run()方法
        public void Run()
        {
            System.Console.WriteLine("一头牛正以 {0} 米每秒的速度奔跑", this._Speed);
            this._Distance += this._Speed;
        }
        //实现IShoutable.Shout()方法
        public void Shout( )
        {
            System.Console.WriteLine("一头牛正在嚎叫......");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //定义IRunable引用,并初始化为一个Cow对象
            IRunable run = new Cow( );
            //直接使用IRunable,它实际上是Cow
            run.Speed = 10;
            run.Run( );
            System.Console.WriteLine("1-总路程:{0}", run.Distance);
            run.Speed = 20;
            run.Run( );
            System.Console.WriteLine("2-总路程:{0}", run.Distance);

            MultInterface( );
        }

        static void MultInterface()
        {
            Cow aCow = new Cow( );
            IRunable run = aCow;
            IShoutable shout = aCow;
            run.Speed = 2.6f;
            run.Run( );
            shout.Shout( );

            aCow.Speed = 9.5f;
            aCow.Run( );
            aCow.Shout( );
        }
    }
}

不大明白这个接口的作用,不过还是留着吧,加油!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值