How to choose between private member and let binding?

后端 未结 3 1796
陌清茗
陌清茗 2021-01-17 21:29

When writing a private method that has no need to access other members of the same class, how do you choose between private member and let binding?

  • I tend to u
相关标签:
3条回答
  • 2021-01-17 21:48

    let bindings in a class are private. The main difference I think of between let and a private member are that let bindings cannot be overloaded, and are called with name() rather than this.Name(). As such, I think it's a mostly stylistic choice.

    0 讨论(0)
  • 2021-01-17 21:57

    let bindings cannot be accessed through the class instance but private method can. For examples:

    type A() =
        let someUtil() = "util code"
    
        member private this.AnotherUtil() = "anotherUtil"
    
        member private this.DoSomething() =
           let anotherA = A()
           A.someUtil()  // compilation failed
           A.AnotherUtil() // ok
    
    0 讨论(0)
  • 2021-01-17 22:07

    The relevant portion of the spec is section 8.6.2. It states:

    The compiled representation used for values declared in “let” bindings in classes is either:

    • A value that is local to the object constructor (if the value is not a syntactic function, is not mutable and is not used in any function or member).

    • An instance field in the corresponding CLI type (if the value is not a syntactic function, but is used in some function or member).

    • A member of the corresponding CLI type (if the value is a syntactic function).

    Also:

    Non-function let-bindings that are not used in either the members of a type or a function binding are optimized away and become values that are local to the resulting CLI constructor. Likewise, function bindings are represented as instance members.

    I prefer let bindings to private members because they're more "functional," i.e., they emphasize "what" over "how." The compiler takes care of the optimal compiled form.

    0 讨论(0)
提交回复
热议问题