简体   繁体   English

F#:静态let和静态成员

[英]F# : static let and static member

I'm a noob in F# and currently reading Expert in F# 3.0. 我是F#的菜鸟,目前正在阅读F#3.0的专家。 Its the first compiled language I'm learning (I just know to program in R) 它是我正在学习的第一种编译语言(我只知道用R编程)

on chapter 6, p.117, we are introduced without much ceremony static let and static member. 在第6章,第117页上,我们介绍了没有太多仪式的静态租用和静态成员。 i don't really understand what it is 我不太明白那是什么

type Vector2D(dx : float, dy : float) =
     static let zero = Vector2D(0.0, 0.0)
     static let onex = Vector2D(1.0, 0.0)
     static let oney = Vector2D(0.0, 1.0)
     /// Get the zero vector
     static member Zero = zero
     /// Get a constant vector along the X axis of length one
     static member OneX = onex
     /// Get a constant vector along the Y axis of length one
     static member OneY = oney 

There is no example who to proceed further in the book. 本书中没有谁可以继续进行下去。

I'm typing this in F# interactive. 我在F#交互式中输入此内容。 From there, how do I construct a variable x whose value is zero (or onex...)? 从那里,如何构造一个值为零(或onex ...)的变量x?

I'm trying the following. 我正在尝试以下。 Nothing works 没用

let x = Zero;;
let y = Vector2D(2.0,2.0);; /// ok
y.Zero;;
stdin(237,1): error FS0809: Property 'Zero' is static

in http://fsharpforfunandprofit.com/posts/classes/ there is this example, http://fsharpforfunandprofit.com/posts/classes/中,有此示例,

type StaticExample() = 
    member this.InstanceValue = 1
    static member StaticValue = 2  // no "this"

// test
let instance = new StaticExample()
printf "%i" instance.InstanceValue
printf "%i" StaticExample.StaticValue

so i would have expected y.Zero;; 所以我会期望y.Zero;; to yield something above ?... 产生以上的东西?...

thanks. 谢谢。 sorry the question is so basic. 对不起,这个问题是如此基本。 If someone can explain me what it is about... 如果有人能解释我的意思...

So the basic difference is that static members don't belong to an instance of a class. 因此,基本区别在于静态成员不属于类的实例。

rather than y.Zero , you get Vector2D.Zero . 而不是y.Zero ,您将获得Vector2D.Zero

To a first approximation you can think of these examples of properties of the type. 大概可以想到这些类型的属性的例子。

static members belong to the type on which they are declared and are accessed by the fully qualified type and member name. 静态成员属于声明它们的类型,并且可以通过完全限定的类型和成员名称进行访问。 In this instance 在这种情况下

let zero = Vector2D.Zero
let oneX = Vector2D.OneX
let oneY = Vector2D.OneY

The Vector2D type does not currently have any instance members, but if it did, these would be accessible on an instance of Vector2D Vector2D类型当前没有任何实例成员,但是如果有,则可以在Vector2D实例上访问这些Vector2D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM