如何尽可能友好地向 C# 和 F# 公开类型? [英] How to expose the type as friendly as possible to both C# and F#?

查看:13
本文介绍了如何尽可能友好地向 C# 和 F# 公开类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我用 F# 编写了一个模块

For example, if I have written a module in F#

module Lib

type A =
    member this.x1 x = ...

let helpa x = ...
let helpb x = ...

type B =
    member this.y1 x = ...

let helpc x = ...

typeA with
    member this.x2 x = ...
typeB with
    member this.y2 x = ...

它通过 open Lib 在 F# 中运行良好,但是,如果我想在 C# 中使用它(我只对 Lib 中的类型和成员函数感兴趣),每次我创建一个类型时,我都必须new Lib.A(...).它变得相当烦人,无法省略模块名称.调用像 Lib.A.C() 这样的静态方法更麻烦.

It works well in F# by open Lib, However, if I want to consume it in C# (where I am only interested in types and member functions in Lib), each time I create a type I have to new Lib.A(...). It becomes rather annoying there is no way to omit the module names. Calling a static method like Lib.A.C() is even more of a hassle.

然后我尝试将 module 替换为 namespace,每次引入一些​​辅助函数时,我都必须创建一个具有新名称的新模块.有时我可以设法将所有辅助函数重新排列到 1 个模块中,但这会以某种方式导致代码可读性降低.

Then I try to replace module with namespace, each time I introduce some helper functions I have to create a new module with a new name. Occasionally I can manage to rearrange all helper functions into 1 module, but that would result in less readable code somehow.

什么是更好的结构?

希望我有:在 C# 中使用 * = Lib.*.

推荐答案

我想你已经在你的答案中提到了最好的选择 - 在顶部定义带有 namespace 声明的文件(这样,你可以在 C# 中只编写 using Lib),然后将所有辅助函数放在模块中.

I think you already mentioned the best option in your answer - define the file with namespace declaration at the top (this way, you can write just using Lib in C#) and then place all helper functions in modules.

与某种类型(例如与A)明确关联的辅助函数可以放入名为A的模块中(类似于List中的F#函数List<'T> 类型关联的模块).

Helper functions that are clearly associated with some type (e.g. with A) could be placed into a module named A (similarly to F# functions in the List module that are associated with the List<'T> type).

这需要做更多的工作,因为您需要使用特殊属性标记模块(以避免名称冲突),但是在 F# 和 C# 中都可以轻松使用(我认为使用得当更重要)而不是在构建库时节省一些按键):

This is a bit more work, because you need to mark the module with a special attribute (to avoid name clash), but it will be easy to use from both F# and C# (and I think having nice use is more important than saving a few keystrokes when building the library):

namespace Lib

// Declaration of the 'A' type and helper functions in 'A' module 
type A() =
  member this.x1 x = 10

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module A = 
  let helpa (x:A) = x.x1
  let helpb (x:A) = x.x1

// Declaration of the 'B' type and helper functions in 'B' module 
type B() =
  member this.y1 x = 10

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module B = 
  let helpc (x:B) = x.y1

// Member augmentations for easy use from C#
type A with
    member this.x2 x = A.helpa this
type B with
    member this.y2 x = B.helpc this

这篇关于如何尽可能友好地向 C# 和 F# 公开类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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