简体   繁体   English

F#:究竟应该如何使用 ToString?

[英]F#: How exactly is ToString supposed to be used?

I am learning F# but I just don't understand how I am supposed to use ToString.我正在学习 F#,但我只是不明白我应该如何使用 ToString。 Below are a few attempts.下面是一些尝试。 The syntax errors are saying it is expecting type string but that it is actually type uint -> string.语法错误说它需要类型 string 但它实际上是类型 uint -> string。 So it doens't actually appear to be invoking a function?所以它实际上似乎并没有调用一个函数? Could this be explained?这可以解释吗? This seems like such a simple thing to do but I can't figure it out.这似乎是一件很简单的事情,但我无法弄清楚。

open System
open System.IO
open FSharp.Data

[<EntryPoint>]
let main (args: string[]) =
    let htmlPage = HtmlDocument.Load("https://scrapethissite.com/")

    printfn  "%s" htmlPage.ToString // This causes a syntax error
    
    htmlPage.ToString
    |> (fun x -> printfn "%s" x) // This also causes a syntax error

    0

.ToString is a method, not a value. .ToString是一个方法,而不是一个值。 In F# every method and every function has a parameter.在 F# 中,每个方法和每个函数都有一个参数。 In fact, that's how functions differ from values (and methods from properties): by having a parameter.事实上,这就是函数与值(以及来自属性的方法)的不同之处:具有参数。

Unlike in C#, F# methods and functions cannot be parameterless.与 C# 不同,F# 方法和函数不能是无参数的。 If there is nothing meaningful that you'd want to pass to the method, that method would still have one parameter of type unit .如果您想传递给该方法没有任何有意义的内容,则该方法仍将有一个类型为unit参数。 See how this is visible in the error message?看看这是如何在错误消息中看到的? unit -> string is the type. unit -> string是类型。

To call such method, you have to pass it the parameter.要调用这样的方法,您必须将参数传递给它。 The sole value of type unit is denoted () .类型unit的唯一值表示为() So to call the method you should do:所以要调用你应该做的方法:

    htmlPage.ToString ()
    |> printfn "%s"

Your first example is a bit more complicated.你的第一个例子有点复杂。 The following would not work:以下将不起作用:

printfn "%s" htmlPage.ToString ()

Why?为什么? Because according to F# syntax this looks like calling printfn and passing it three parameters: first "%s" , then htmlPage.ToString , and finally () .因为根据 F# 语法,这看起来像是调用printfn并向其传递三个参数:首先是"%s" ,然后是htmlPage.ToString ,最后是() To get the correct order of calls you have to use parentheses:要获得正确的调用顺序,您必须使用括号:

printfn "%s" (htmlPage.ToString ())

And finally, general piece of advice: when possible try to avoid methods and classes in F# code.最后,一般建议:尽可能避免在F#代码中使用方法和类。 Most things can be done with functions.大多数事情都可以用函数来完成。 In this particular case, the ToString methods can be replaced with the equivalent function string :在这种特殊情况下, ToString方法可以替换为等效的函数string

printfn "%s" (string htmlPage)

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

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