接口类型的变量引用实现接口的类的实例

一、前言

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

二、实例

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,实现了方法在运行时的动态绑定,充分利用了“一个接口,多个方法”  

三、注意

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

      

转载于:https://www.cnblogs.com/YanYongSong/p/5242377.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值