继承之接口知识点和思考练习

知识点

接口是一种数据结构,它包含了一组函数型方法,通过这组数据结构,用户代码可以调用组件的功能。

访问修饰符 interface 接口名
{
    接口体
}

接口声明时,注意一下几个方面:
1)访问修饰符只能是new public protected internal private中的一种
2)接口名以大写字母"I"开头
3)接口体只限于方法、属性、事件和索引器的声明,不能包括构造函数、析构函数、常数和字段等
4)接口不能包含任何实现方法
5)在接口体中声明方法时,不能包含public修饰符,也不能包含除new修饰符以外的其他修饰符。只需给出返回类型、方法名和参数列表,并以分号结束。

C#语言中一个类只可以继承一个基类,但可以允许多重接口实现,即一个类可以同时实现多个接口(继承多个接口)。当继承基类和多接口时,基类是继承列表中的第一项。

如果一个类实现了(继承了)两个接口,且这两个接口包含具有相同名称的方法,那么在类中实现该方法将导致两个接口都使用该方法作为它们的实现,就会出现不确定情况。C#
中可以显式地实现接口方法,通过接口名称和一个点来命名方法以确定成员方法实现的是哪一个接口。

 

思考练习

using System;
namespace InterfaceName
{
    public class BaseClass
    {
        protected static double x, y;
        protected const double PI = Math.PI;
        public BaseClass(double x1, double y1)
        {
            x = x1;
            y = y1;
        }

        public void Show()
        {
            Console.WriteLine("这里是调用BaseClass类的show方法");
        }
    }
    public interface IFunction1
    {
        double Area();
    }

    public class Sphere : BaseClass, IFunction1
    {
        public Sphere(double x, double y) : base(x, y) { }
        public double Area()
        {
            return BaseClass.PI * BaseClass.x * BaseClass.y;
        }

    }
    public class Program
    {
        static void Main()
        {
            Sphere sphere1 = new Sphere(6, 7);
            Console.WriteLine("The sphere's area is {0}", sphere1.Area());
            Console.ReadLine();
        }
    }

}

using System;
namespace InterfaceName
{
    public class BaseClass
    {
        protected static double x, y;
        protected const double PI = Math.PI;
        public BaseClass(double x1, double y1)
        {
            x = x1;
            y = y1;
        }

        public void Show()
        {
            Console.WriteLine("这里是调用BaseClass类的show方法");
        }
    }
    public interface IFunction1
    {
        double Area();
    }
    public interface IFunction2
    {
        double Area();
    }
    public class Sphere : BaseClass, IFunction1, IFunction2
    {
        public Sphere(double x, double y) : base(x, y) { }
        double IFunction1.Area()//一旦用了这种方式,就不能加访问修饰符
        {
            return BaseClass.PI * BaseClass.x * BaseClass.y;
        }
        double IFunction2.Area()
        {
            return BaseClass.PI * BaseClass.x * BaseClass.x;
        }
    }
    public class Program
    {
        static void Main()
        {
            Sphere sphere1 = new Sphere(6, 7);//继承了两个接口,两个接口又有相同名的方法,必须通过定义接口的对象(看似如此),再将派生类的对象赋予它,由接口对象进行访问各自的方法
            IFunction1 ifn1 = sphere1;
            Console.WriteLine("The sphere's area is {0}", ifn1.Area());
            IFunction2 ifn2 = sphere1;
            Console.WriteLine("The sphere's area is {0}", ifn2.Area());
            Console.ReadLine();
        }
    }

}
posted on 2009-09-25 21:49  友闻语上  阅读(193)  评论(0编辑  收藏  举报