共用方式為


使用 .NET CLI 開始使用 F#

本文涵蓋如何使用 .NET CLI 在任何作系統 (Windows、macOS 或 Linux) 上開始使用 F#。 它會使用主控台應用程式所呼叫的類別庫來建置多項目解決方案。

先決條件

若要開始,您必須安裝最新的 .NET SDK

本文假設您知道如何使用命令行,並擁有慣用的文本編輯器。 如果您尚未使用它, Visual Studio Code 是 F# 文字編輯器的絕佳選項。

建置簡單的多專案方案

開啟命令提示字元/終端機,並使用 dotnet new 命令來建立名為 FSharpSample的新方案檔:

dotnet new sln -o FSharpSample

執行上一個命令之後,會產生下列目錄結構:

FSharpSample
    ├── FSharpSample.sln

撰寫類別庫

將目錄變更為 FSharpSample

使用 dotnet new 命令在 src 資料夾中建立名為 Library 的類別庫專案。

dotnet new classlib -lang "F#" -o src/Library

執行上一個命令之後,會產生下列目錄結構:

└── FSharpSample
    ├── FSharpSample.sln
    └── src
        └── Library
            ├── Library.fs
            └── Library.fsproj

以下列程式碼取代 Library.fs 的內容:

module Library

open System.Text.Json

let getJson value =
    let json = JsonSerializer.Serialize(value)
    value, json

使用 Library 命令將專案FSharpSample新增至解決方案。 此命令將專案新增至解決方案檔案,讓解決方案可以追蹤和建置它:

dotnet sln add src/Library/Library.fsproj

執行 dotnet build 以建置專案。 建置時將會還原未解決的相依性。

撰寫取用類別庫的主控台應用程式

使用 dotnet new 命令在 src 資料夾中建立名為 App 的主控台應用程式。

dotnet new console -lang "F#" -o src/App

執行上一個命令之後,會產生下列目錄結構:

└── FSharpSample
    ├── FSharpSample.sln
    └── src
        ├── App
        │   ├── App.fsproj
        │   ├── Program.fs
        └── Library
            ├── Library.fs
            └── Library.fsproj

以下列程式碼來取代 Program.fs 檔案的內容:

open System
open Library

[<EntryPoint>]
let main args =
    printfn "Nice command-line arguments! Here's what System.Text.Json has to say about them:"

    let value, json = getJson {| args=args; year=System.DateTime.Now.Year |}
    printfn $"Input: %0A{value}"
    printfn $"Output: %s{json}"

    0 // return an integer exit code

使用 Library專案新增參考。 此命令會將元素 <ProjectReference> 新增至 App.fsproj 檔案,以告知編譯器 App 專案相依於 Library 專案:

dotnet add src/App/App.fsproj reference src/Library/Library.fsproj

上一個命令會將下列 XML 新增至 App.fsproj 檔案:

<ItemGroup>
  <ProjectReference Include="..\Library\Library.fsproj" />
</ItemGroup>

小提示

如果您略過此步驟並嘗試建置 App 專案,您會收到編譯錯誤,因為 Library 找不到模組。 如果發生這種情況,您可以執行 dotnet add reference 命令或手動將上述元素新增至 <ProjectReference> App.fsproj 檔案。

使用 App 命令將FSharpSample專案新增至dotnet sln add方案:

dotnet sln add src/App/App.fsproj

使用 dotnet restore 還原 NuGet 相依性,然後執行 dotnet build 以建置專案。

將目錄變更為 src/App 主控台專案,並執行傳遞 Hello World 為自變數的專案:

cd src/App
dotnet run Hello World

您應該會看見下列結果:

Nice command-line arguments! Here's what System.Text.Json has to say about them:
Input: { args = [|"Hello"; "World"|] year = 2021 }
Output: {"args":["Hello","World"],"year":2021}

後續步驟

接下來,請參閱 F# 導覽 ,以深入瞭解不同的 F# 功能。