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

查看:60
本文介绍了如何将类型对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.

然后,每次尝试引入一些辅助函数时,我都必须用namespace替换module,必须使用新名称创建一个新模块.有时,我可以设法将所有辅助函数重新排列为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.

对此有什么更好的结构?

What would be a better structure for this?

希望我拥有C#的Using * = Lib.*.

推荐答案

我认为您已经在答案中提到了最佳选择-定义文件并在顶部使用namespace声明(这样,您可以只编写在C#中),然后将所有辅助函数放在模块中.

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.

Helper函数放入名为A的模块中(类似于与List<'T>类型关联的List模块中的F#函数)

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天全站免登陆