f# - 不使用抽象类而不是接口(interface)的原因?

标签 f#

我正在考虑使用具有所有抽象成员的抽象类而不是接口(interface),以避免显式接口(interface)实现样板代码。所以而不是

type IMyInterface =
    abstract Name : string
    abstract Text : string

type MyClass() =
    member __.Name = "name"
    member __.Text = "text"
    interface IMyInterface with
        member this.Name = this.Name
        member this.Text = this.Text

我本来有
[<AbstractClass>]
type MyAbstractClass() =
    abstract Name : string
    abstract Text : string

type MyClass() = 
    inherit MyAbstractClass()
    override __.Name = "name"
    override __.Text = "text"

我应该在这里注意任何警告或暗示?

最佳答案

您应该意识到并做出有意识的决定的唯一一件事是,一个类只能从一个类继承,但可以实现许多接口(interface)。

除此之外,关于使用抽象类或接口(interface)的一些建议:

  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.


http://msdn.microsoft.com/en-us/library/scsyfw1d%28vs.71%29.aspx

就个人而言,我觉得这些建议是正确的。特别是另一方面,接口(interface)一旦创建就不能更改。如果需要新版本的接口(interface),则必须创建一个全新的接口(interface)。 是非常重要的一点。

关于f# - 不使用抽象类而不是接口(interface)的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5768543/

相关文章:

recursion - F# : A recursive value that can reference itself

f# - 如何调用ionide f# REPL

F# 使用 DataReader

f# - 以乘法优先级解析 "x y z"

entity-framework - 是否可以在 F# 中实现 IDbSet<T> 接口(interface)?

.net - 如何在 F# 中的 .txt 文件中间添加一行

f# - 这种类型注释是如何工作的,为什么另一个不能?

visual-studio - 使用取消引用库和 Visual Studio 2015 运行 xunit 测试时出错 - 找不到方法

F# SignalR 动态类

c# - 您如何跟踪线程/线程上下文?