在F#中使用哪个,抽象类或接口? [英] Which to use , abstract class or interface in F#?

查看:57
本文介绍了在F#中使用哪个,抽象类或接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

曾经骗人的F#来自C#背景.

Been grokking F# coming from a C# background.

在C#中,决定何时使用接口和何时使用抽象类有明显的区别.在F#中,我看到两者几乎融为一体.我了解到,就CLR而言,在F#中已经完成了与c#相同的操作,但是在使用F#进行编程时最佳实践"是什么?

In C# there is a clear difference in deciding when to use interfaces and when to use abstract classes. In F# I see the two blurring almost into one. I understand under the hood that the same is being done in F# as c# as far as the CLR is concerned, but what is the "best practise" when programming in F# to use?

我应该完全避免类继承吗?

Should I avoid class inheritance altogether?

推荐答案

我认为接口的使用往往比抽象类(与C#这样的面向对象的语言相比)要频繁得多.

I think that interfaces tend to be used much more frequently than abstract classes (compared to object-oriented languages like C#).

在很多情况下,您不需要两者中的任何一个,因为您可以编写更高阶的函数(将函数作为参数,而不是将接口作为参数).但是,有时您可能有两个总是一起使用的功能-在这种情况下,您可以将两个功能分组到一个接口中:

In many cases, you don't need any of the two, because you can just write higher-order function (that takes a function as an argument, instead of taking an interface as an argument). However, sometimes you may have two functions that are always used together - in that case, you can group two functions into an interface:

// Instead of using higher-order function
val foo : (int -> string) -> (string -> int) -> ...

// ..we can define an interface
type TwoWayConversion = 
  abstract ToString : int -> string
  abstract FromString : string -> int

val foo : TwoWayConversion -> ...

我认为这是非常有用的F#编程模式,它以完美的功能样式使用接口.

I think that this is quite useful F# programming pattern that uses interfaces in a perfectly functional style.

另一方面,我仅在编写应该从C#使用的面向对象代码(例如,实现F#抽象类的C#代码)时才使用抽象类-因为从C#的角度来看,这是自然的可扩展性点看法.但是,我认为惯用的F#代码使用的扩展点与C#不同(例如,以函数/接口作为参数),因此您实际上并不需要抽象类.

On the other hand, I would use abstract classes only when writing object-oriented code that is supposed to be used from C# (e.g. C# code implementing your F# abstract class) - because that's a natural extensibility point from the C# point of view. However, I think that idiomatic F# code uses different extensibility points than C# (e.g. taking function/interface as an argument), so you don't really need abstract classes.

这篇关于在F#中使用哪个,抽象类或接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆