F#入门-第四章 面向对象-第七节 接口

接口
    接口只具有抽象方法和属性。同时,接口不提供实现。也就是说,不能直接实例化接口,必须通过后文叙述的Object Expression,用类来实现接口。


    接口的书写方法如下所示。

 接口
         type 接口名 = interface
    声明继承
    成员定义
    end


    interface与end在#light语句中可以省略。

    下例中将抽象方法一节中的介绍中创建的抽象方法改变成接口。

接口的例子
type AnimalInterface = interface
    abstract Bark : unit -> unit
    end;;


    下例中使用接口将上一节抽象方法中的代码进行改写。

使用接口的例子
type Dog = class
    new () = {}
    interface AnimalInterface with
        member x.Bark () = System.Console.WriteLine("wan wan")
    end
end;;
type Cat = class
    new () = {}
    interface AnimalInterface witme
        member x.Bark () = System.Console.WriteLine("nya- nya-")
    end
end;;

//let a = new Dog() in a.Bark();;
let a = new Dog() in (a :> AnimalInterface).Bark();;
let b = new Cat() in (b :> AnimalInterface).Bark();;

 

    接口的实现如下文所示
 

 接口的实现
    interface 接口名 with
        值或成员的定义
    end


    稍嫌麻烦的是,不能写成象上例中注释掉的部分那样的写法.如果想不转换类型而可以完成上述功能的话,必须要写成下面这样。

使用接口的例子之2
type AnimalInterface = interface
    abstract Bark : unit -> unit
    end;;
type Dog = class
    new () = {}
    interface AnimalInterface with
        member x.Bark () = System.Console.WriteLine("wan wan")
    end
    member x.Bark () = System.Console.WriteLine("wan wan")
end;;
type Cat = class
    new () = {}
    interface AnimalInterface with
        member x.Bark () = System.Console.WriteLine("nya- nya-")
    end
    member x.Bark () = System.Console.WriteLine("nya- nya-")
end;;

let a = new Dog() in a.Bark();;
let b = new Cat() in b.Bark();;


    但是,这样的话同样内容的函数需要写两遍,就失去了接口的意义了。还有,接口内的函数与类内的函数也分开来执行了,

接口的继承
    接口可以继承接口。继承接口时使用inherit关键字。

接口的继承
type IA = interface abstract One : int -> int end;;
type IB = interface abstract Two : int -> int end;;
type IC = interface
    inherit IA
    inherit IB
    abstract Three : int -> int
end;;


    一个接口可以继承多个接口。上例中IC继承IA和IB,带有One,Two,Three三个抽象方法。在下例中将这三个方法作为函数进行实现。

继承后的接口的利用
type ClassWithIC = class
    new () = {}
    interface IC with
        member x.One n = 1
        member x.Two n = 2
        member x.Three n = 3
    end
end;;


    象这样,也可以象利用普通接口那样利用继承后创建的接口。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值