c# 第四课 interfaces

本文深入探讨了C#中的接口与抽象类的概念,解释了接口如何作为合同来规范类的行为,并通过实例展示了如何实现接口与抽象类。重点介绍了C#允许接口的多重继承与单一基类继承的特点,以及接口与抽象类之间的相似性和区别。
An interface is a contract(协定) that guarantees to a client how a class or struct will behave.
When a class implements an interface(实现一个接口), it tells any potential(可能的) client “I guarantee I’ll support all the methods, properties, events, and indexers of the named interface.”
These contracts are made manifest(表明) using the interface keyword, which declares a reference type(引用类型) that encapsulates(封装) the contract.
interface ICompressible
{
    void Compress();
    void Decompress();
}
interface ILoggedCompressible 
: ICompressible
{
    void LogSavedBytes();
}
public class Document : ILoggedCompressible 
{
    // 实现ICompressible
    public void Compress(){ …}
    public void Decompress() { …}
    // 实现ILoggedCompressible 
     public void LogSavedBytes() { …}
// 要实现所有的接口成员

 

 

as operator

foreach (Document doc in folder)
{
        IStorable isDoc = doc as IStorable;
        if (isDoc != null)
        {
                isDoc.Read();
        }else{
                Console.WriteLine("IStorable not supported");doc.Encrypt();
        }
…
}

as 有左右两个操作数
Casts the left operand to the type specified by the right operand.
Returns null if the cast fails.
Interface Vs. Abstract Class
Interfaces are very similar to abstract classes.
C# doesn’t allow multiple inheritance with classes.
C# does allow to implement any number of interfaces and derive from one base class.

转载于:https://www.cnblogs.com/GSONG/p/4399062.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值