MyPersistence

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

一、前言

  接口的灵活性就在于“规定了一个类必须做什么,而不管你如何做”。我们可以定义一个接口类型的变量来引用实现接口的类的对象,当这个引用来调用方法时,它会根据实际引用的类的实例来判断具体调用哪个方法。

二、实例

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

using CSharpLib;

 

namespace foundation
{
interface Inter
{
void fun();
}

public class A : Inter
{
public void fun()
{
Console.WriteLine("This is A");

}
}

public class B : Inter
{
public void fun()
{
Console.WriteLine("This is B");
Console.Read();
}

public void test()
{
Console.WriteLine("This is test");
}
}

class Program
{

static void Main(string[] args)
{
Inter a;
a = new A();
a.fun();
a = new B();
a.fun();

}
}

}

输出结果为:

    This is A
    This is B

上例中类A和类B是实现接口Inter的两个类,分别实现了接口的方法fun(),通过将类A和类B的实例赋给接口引用a,实现了方法在运行时的动态绑定,充分利用了“一个接口,多个方法”  

三、注意

  当接口变量在调用其实现类的对象的方法时,该方法必须已经在接口中被声明,而且在接口的实现类中该实现方法的类型和参数必须与接口中所定义的精确匹配。

      

posted on 2016-03-04 15:51  MyPersistence  阅读(1401)  评论(0编辑  收藏  举报