C#每日一课(二十)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/advent86/article/details/83616952
  • C#接口
    接口定义了所有类继承时需要遵守的规则,接口定义的是这个规则是什么,派生类则定义出这个规则怎么做。
    接口只能包含成员的声明,成员的定义需要由派生类来进行实现。
    抽象类与接口类似,但是它更适用于只有部分方法需要由派生类实现时。

  • 声明接口
    接口声明使用interface关键字声明,与类的声明相似,默认为public的,其中的方法都只做声明无具体的实现
    如:

public interface A
{
	//接口成员
	void toDo1();
	string toDo2();
}

在Visual Studio中新增C#控制台应用程序chapter15_001
新增接口Person

namespace chapter15_001
{
    interface Person
    {
        void toDo();
    }
}

新增派生类Student

namespace chapter15_001
{
    class Student : Person
    {
        public void toDo()
        {
            Console.WriteLine("Student,doSomething~~~~");
        }
    }
}

新增派生类Teacher

namespace chapter15_001
{
   class Teacher : Person
   {
       public void toDo()
       {
           Console.WriteLine("Teacher,doSomething~~~~");
       }
   }
}

在Main方法中进行测试调用

static void Main(string[] args)
{
       Student stu = new Student();
       Teacher tea = new Teacher();

       stu.toDo();
       tea.toDo();
       Console.ReadKey();
}

编译运行结果如下:
编译运行结果
从上面的实例可以看到
1.接口中对方法做定义
2.需要在派生类中对接口定义的所有方法定义具体的实现
3.在实际调用时编译器根据实际调用的类来确定具体的实现(动态多态实现)

猜你喜欢

转载自blog.csdn.net/advent86/article/details/83616952