简体   繁体   中英

Is it possible for a F# type to “inherit” from a C# class?

I have used Haskell a bit in my days but it was a long time ago so I decided to take a look at F#. I do a lot of daily development using C, C++ and C#.

I noticed that you could expose F# types as classes in C# when compiling F# to a dll. But then I came to think. I have a few C# classes I would like to put the logic of in F# (to try it out). But a lot of the existing C# code handles a lot of objects by their base class (which is very rudimentary). Would it be possible to use that base class from C# as a base for the F# types? Or can F# only inherit from other F# types?

The reason behind this would be to keep the base class as part of the main C# project and the specific dlls (kind of like plugins based on the given contract by the base class) could be written in F#. If it can't be done I would have to add yet another F# project that contains only the base class which feels a bit overly complicated.

Yes. It is possible.

type SomeClass =
    inherit SomeCSharpBase

Here are some more details:

Inheritance (F#)

F# classes can inherit from .NET classes:

type FSharpClass() =
    inherit System.AccessViolationException()

Some other F# types such as records, discriminated unions cannot inherit from classes, but they can implement interfaces:

type FSharpRecord =
    { d : System.IDisposable }
    interface System.IDisposable with
        member this.Dispose() = this.d.Dispose()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM