【interface】C#interface定义及使用浅析

1 篇文章 0 订阅

转载自:http://developer.51cto.com/art/200908/147442.htm

C# interface定义及使用的问题:接口定义以大写字母I开头。方法只定义其名称,在C#中,方法默认是公有方法;用public修饰方法是不允许的,否则会出现编译错误;接口可以从别的接口继承,如果是继承多个接口,则父接口列表用逗号间隔。


C# interface可以通过类来实现,当类的基列表同时包含基类和接口时,列表中首先出现的是基类;类必须要实现其抽象方法;

C# interface定义及使用实例:

using System;  
namespace Dage.Interface   
{  
    //打印机接口  
    public interface IPrint  
    {  
        string returnPrintName();  
    }  
}  
//C# interface应用实现  
using System;  
using Dage.Interface;  
namespace Dage.Print  
{  
    //HP牌打印机类  
    public class HP: IPrint  
    {  
        public string returnPrintName()  
        {  
            return "这是HP牌打印机";  
        }  
    }  
}  
//C# interface应用实现  
using System;  
namespace Dage.Print  
{  
    //Eps牌打印机类  
    public class Eps: IPrint  
    {  
        public string returnPrintName()  
        {  
            return "这是Eps牌打印机";  
        }  
    }  
}  
//C# interface应用实现  
using System;  
using Dage.Interface;  
namespace Dage  
{  
    //打印类  
    public class Printer  
    {  
        public Printer()  
        {}  
        public string PrintName(IPrint iPrint)  
        {  
            return iPrint.returnPrintName();  
        }  
    }  
}  
//C# interface应用实现  
//--WinFrom中调用代码:  
private void button1_Click(object sender, System.EventArgs e)  
{  
    Printer p= new Printer();  
    switch (this.comboBox1.Text)  
    {  
        case "HP":  
        MessageBox.Show(p.PrintName(new HP()));  
            break;  
        case "Eps":  
        MessageBox.Show(p.PrintName(new Eps()));  
            break;  
            default:  
        MessageBox.Show("没有发现这个品牌!");  
            break;  
    }  
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值