【问题标题】:Duplicate definition of type or module when defining a type and a module with the same name定义同名的类型和模块时重复定义类型或模块
【发布时间】:2015-04-06 21:23:00
【问题描述】:

据我了解,约定是定义你的类型,然后在它之后定义一个同名的模块,以及对该类型进行操作的函数。

我正在尝试这样做,所以我有这个代码

namespace Rand

type ImmutableRandom

module ImmutableRandom =
    open System

    val fromSeed : int -> ImmutableRandom
    val int : ImmutableRandom -> int
    val intInRange : ImmutableRandom -> int -> int -> int
    val double : ImmutableRandom -> double
    val next : ImmutableRandom -> ImmutableRandom

我收到 ImmutableRandom(模块名称带下划线)正在重新定义类型或模块的错误。

在同一个项目中,相同的设置适用于不同的类型,唯一的区别是该类型有一个泛型参数,而 ImmutableRandom 没有。

我做错了什么?

【问题讨论】:

标签: f#


【解决方案1】:

在您的模块上使用CompilationRepresentation 属性,使其在源代码中具有相同的名称,但在 IL 中不同:

namespace Rand

type ImmutableRandom

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module ImmutableRandom =
    open System

    val fromSeed : int -> ImmutableRandom
    val int : ImmutableRandom -> int
    val intInRange : ImmutableRandom -> int -> int -> int
    val double : ImmutableRandom -> double
    val next : ImmutableRandom -> ImmutableRandom

这将导致模块在 IL 中命名为 ImmutableRandomModule(因此来自 F# 以外的语言)。与静态成员相比,这有一些优点,在​​这个答案中得到了很好的总结:F# code organization: types & modules

【讨论】:

    【解决方案2】:

    如果类型是通用的,则此方法有效。否则,存在编译器无法自行解决的歧义。

    如果您真的觉得需要对非泛型类型执行此操作,请将所有函数定义为该类型的静态成员。有点不优雅,但你得到了相同的表面 API。

    【讨论】:

    • 好的。感谢您的澄清。
    猜你喜欢
    • 2020-06-27
    • 2017-03-06
    • 1970-01-01
    • 2018-02-24
    • 2017-02-17
    • 2015-05-01
    • 2015-01-30
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多