从内部类型访问外部类型的成员

Access member of outer type from inner type

我想知道我必须做什么才能编译以下 F# 代码:

type MyType() =
  [<Literal>]
  let outer = "Foo"

  type MyInnerType() =
    [<Literal>]
    let inner = outer + ".Bar"

编译器引发错误 FS0039 "The value or constructor 'outer' is not defined"。这是不可能的还是设计不允许的?

我想在 xUnit 测试方法的属性中使用这些值,该方法要求这些值是编译时常量(因此 [<Literal>]):

    [<Trait("", inner)>]
    [<Fact>]
    let test() =
      Assert.Equal(3, 1 + 2)

我假设 outer 是一个 class 字段,因此您需要在引用其内部之前实例化 class。

这可能对你有用:

type MyType() =
  static member outer = "Foo"

  type MyInnerType() =
    let inner = MyType.outer + "Bar"

可能对您有用的是跨 F# modules 的文字表达式。以下片段

module A =
    [<Literal>]
    let A = "A"

    module B =
        [<Literal>]
        let B = A + "B"

[<Literal>]
let C = A.A + A.B.B + "C"

fsi 消耗为

module A = begin
  val A : string = "A"
  module B = begin
    val B : string = "AB"
  end
end
val C : string = "AABC"

这意味着 F# 编译器很乐意将来自不同模块(可能嵌套)的文字和常量表达式组合成一个常量表达式。