接口的简单应用

本文通过一个具体的C#代码示例,详细讲解了如何定义和使用接口,包括接口的声明、类的实现以及如何调用接口方法。通过实例展示了接口在面向对象编程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//No:1  首先,我们要封装一个接口,接口中不要实现具体的方法(说白了这就是一个架子而已!)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    interface Ipeople //接口声明:
    {
        int w
        {
            get;
            set;
        }
        int h
        {
            get;
            set;
        }
    }

//No:2 接口的调用
    class MyPoint : Ipeople //实现接口
    {

        //这里的类就必须要实现接口中未实现的方法
        private int myW;
        private int myH;
        public MyPoint(int w, int h)
        {
            myW = w;
            myH = h;
        }
        public int w
        {
            get { return myW; }
            set { myW = value;}
        }
        public int h
        {
            get { return myH; }
            set { myH = value;}
        }
    }

//No:2 接口的调用
    class Program
    {
        
        static void Main(string[] args)
        {
            MyPoint mp = new MyPoint(35, 170); //传入实际参数
            print(mp);
            Console.Read();
        }
        private static void print(Ipeople ip)
        {
            Console.WriteLine("体重为:{0},身高为:{1}\n", ip.w, ip.h);
        }
    }
}

No : 4结果如下,不知道你是否有所领悟呢。




体重为:35 身高为:170

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值