C# 接口

C# 接口

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

namespace MyInterface
{

    interface PolygonInterface
    {
        //下面声明错误,接口中不能声明字段
        //public string type;

        //接口中默认所有类型均为 public,
        //所以无需声明为 public类型

        // 下面写法错误,接口只能声明方法,不能写方法的实现
        //float Area()
        //{
        //    return 0;
        //}

        float Area();
        int Circumference();
        void Type();
    }


    // TriangleClass 基类继承于 PolygonInterface 接口
    public class TriangleClass : PolygonInterface
    {
        private int edge1; //定义边
        private int edge2;
        private int edge3;

        public TriangleClass() { }

        //设置边长方法
        public void SetEdge(int edge1, int edge2, int edge3)
        {
            this.edge1 = edge1;
            this.edge2 = edge2;
            this.edge3 = edge3;
        }

        // 必须实现接口中的方法 Area()
        public float Area()
        {
            float s = (edge1 + edge2 + edge3) * 0.5f;
            float area = (float)Math.Sqrt(s * (s - edge1) * (s - edge2) * (s - edge3));
            return area;
        }

        // 必须实现接口中的方法 Circumference()
        public int Circumference()
        {
            return edge1 + edge2 + edge3;
        }

        // 必须实现接口中的方法 Type()
        public void Type()
        {
            Console.WriteLine("This is TriangleClass");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //下面错误,接口无法实例化
            //PolygonInterface polygonInterface = new PolygonInterface();

            TriangleClass triangleClass = new TriangleClass();
            triangleClass.SetEdge( 6, 8, 10);

            float area = triangleClass.Area();
            float circum = triangleClass.Circumference();

            triangleClass.Type();
            Console.WriteLine(string.Format("area = {0},  circum = {1}", area, circum));

            Console.WriteLine("\n");
            Console.Read();
        }
    }
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值