目录
2.3 定义类calc并显式实现IArea和ILength接口
接口查询就是实现对象在同一类的不同接口之间切换;即:在一个类实现了多个接口,从类中的一个接口跳转到另外一个接口的过程就是QI(接口查询)。
理论要点:
接口查询(或者叫接口转换)是针对同一个类实现的接口来说的,不同的类实现的接口之间是不能进行QI的
当我们用new关键字实例化了一个类,并将该类实例的引用保存到一个接口类型的变量里面(注:该类实现了该接口)
1 准备工作
新建winform应用程序,添加button1,button2和button3按钮
定义类calc(计算类)、IArea(面积接口)和ILength(长度接口)
2 类和接口的实现
2.1 定义接口IArea
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QI
{
interface IArea
{
void getArea();
}
}
2.2 定义接口ILength
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QI
{
interface ILength
{
void getLength();
}
}
2.3 定义类calc并显式实现IArea和ILength接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QI
{
class calc : IArea, ILength
{
void IArea.get()
{
MessageBox.Show("计算面积接口");
}
void ILength.get()
{
MessageBox.Show("计算长度接口");
}
}
}
3 主窗体的展示
3.1 直接通过接口定义对象
private void button1_Click(object sender, EventArgs e)
{
IArea A = new calc();
A.get();
ILength B = new calc();
B.get();
}
3.2 通过实例化类的方式访问接口方法
无法直接访问
3.3 采用接口查询的方式定义
private void button3_Click(object sender, EventArgs e)
{
IArea IA = new calc();
IA.get();
ILength IL = IA as ILength;
IL.get();
}
类clac实现了四个接口,但是,对象IA目前所能使用的方法和属性就只有接口IArea中所定义的属性和方法,而不能使用ILength接口所定义的属性和方法。但是,如果我们还想使用其它接口(ILength)所定义的方法和属性,那么这个时候就要用到QI
4 运行结果展示