且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

设计用于 F# 和 C# 的 F# 库的***方法

更新时间:2023-02-09 17:09:56

Daniel 已经解释了如何定义您编写的 F# 函数的 C# 友好版本,因此我将添加一些更高级别的注释.首先,您应该阅读 F# 组件设计指南(已被 gradbot 引用).这是一份解释如何使用 F# 设计 F# 和 .NET 库的文档,它应该可以回答您的许多问题.

Daniel already explained how to define a C#-friendly version of the F# function that you wrote, so I'll add some higher-level comments. First of all, you should read the F# Component Design Guidelines (referenced already by gradbot). This is a document that explains how to design F# and .NET libraries using F# and it should answer many of your questions.

在使用 F# 时,基本上可以编写两种库:

When using F#, there are basically two kinds of libraries you can write:

  • F# 库 旨在从 F# 中使用,因此它的公共接口是以函数式风格编写的(使用 F# 函数类型、元组、区分工会等)

  • F# library is designed to be used only from F#, so it's public interface is written in a functional style (using F# function types, tuples, discriminated unions etc.)

.NET 库 旨在用于任何 .NET 语言(包括 C# 和 F#),它通常遵循 .NET 面向对象的风格.这意味着您将大部分功能公开为带有方法的类(有时是扩展方法或静态方法,但大部分代码应在 OO 设计中编写).

.NET library is designed to be used from any .NET language (including C# and F#) and it typically follows .NET object-oriented style. This means that you'll expose most of the functionality as classes with method (and sometimes extension methods or static methods, but mostly the code should be written in the OO design).

在您的问题中,您询问如何将函数组合公开为 .NET 库,但我认为从 .NET 库的角度来看,像您的 compose 这样的函数是太低级的概念.您可以将它们公开为使用 FuncAction 的方法,但这可能不是您首先设计普通 .NET 库的方式(也许您会改用 Builder 模式或类似的东西).

In your question, you're asking how to expose function composition as a .NET library, but I think that functions like your compose are too low level concepts from the .NET library point of view. You can expose them as methods working with Func and Action, but that probably isn't how you would design a normal .NET library in the first place (perhaps you'd use the Builder pattern instead or something like that).

在某些情况下(即在设计与 .NET 库风格不太匹配的数字库时),设计一个混合了 F# 的库是很有意义的.NET 样式在单个库中.***的方法是使用普通的 F#(或普通的 .NET)API,然后提供包装器以在其他风格中自然使用.包装器可以位于单独的命名空间中(例如 MyLibrary.FSharpMyLibrary).

In some cases (i.e. when designing numerical libraries that do not really fit well with the .NET library style), it makes a good sense to design a library that mixes both F# and .NET styles in a single library. The best way to do this is to have normal F# (or normal .NET) API and then provide wrappers for natural use in the other style. The wrappers can be in a separate namespace (like MyLibrary.FSharp and MyLibrary).

在您的示例中,您可以将 F# 实现保留在 MyLibrary.FSharp 中,然后在 MyLibrary 命名空间作为某个类的静态方法.但同样,.NET 库可能具有比函数组合更具体的 API.

In your example, you could leave the F# implementation in MyLibrary.FSharp and then add .NET (C#-friendly) wrappers (similar to code that Daniel posted) in the MyLibrary namespace as static method of some class. But again, .NET library would probably have more specific API than function composition.