1、接口:
接口与抽象类一样,也是表示某种规则,一旦使用了该规则,就必须实现相关的方法。对于C#语言而言,由于只能继承自一个父类,因此若有多个规则需要实现,则使用接口是个比较好的做法。
2、接口的定义
代码如下:
interface接口名
{
方法声明;
}
3、不同接口中若有多个相同名称的方法,则需要显式指定接口名,例如:
4、接口的使用
使用接口也可以实现多态。
代码如下:
代码如下:
classProgram
{
staticvoidMain(string[]args)
{
//提供三个类,完成工资的计算
List<ICalu>list=newList<ICalu>();
list.Add(newBoss());
list.Add(newClert());
list.Add(newClert());
list.Add(newCustomer());
foreach(ICaluempinlist)
{
emp.Calu();//多态
}
}
}
classBoss:ICalu
{
public voidCalu()
{
Console.WriteLine(“计算老板工资”);
}
}
classCustomer:ICalu
{
public voidCalu()
{
Console.WriteLine(“计算客户工资”);
}
}
classClert:ICalu
{
public voidCalu()
{
Console.WriteLine(“计算职员工资”);
}
}
interfaceICalu
{
voidCalu();
}
5、接口应用场合举例
6、接口demo
代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;usingSystem.Text;
namespaceConsoleApplication1{
classProgram {
staticvoidMain(string[]args) {
List<IShow>list=newList<IShow>();
list.Add(newMap());
list.Add(newVoice());
list.Add(newVideo());
list.Add(newThreeD());
foreach(IShowishowinlist) {
ishow.Show(); }
}
}
interfaceIShow {
voidShow(); }
publicclassMap:IShow {
publicvoidShow()
{
Console.WriteLine(“显示图片”); }
}
publicclassVoice:IShow {
publicvoidShow() {
Console.WriteLine(“播放声音”); }
}
publicclassVideo:IShow {
publicvoidShow()
{
Console.WriteLine(“显示视频”); }
} publicclassThreeD:IShow {
publicvoidShow() {
Console.WriteLine(“3D交互”); }
}
}
上述就是C#学习教程:c#接口使用示例分享分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)! 您可能感兴趣的文章:C#接口归纳
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/905349.html