F# - 名稱空間



名稱空間旨在提供一種方法來將一組名稱與另一組名稱區分開來。在一個名稱空間中宣告的類名不會與在另一個名稱空間中宣告的相同類名衝突。

根據 MSDN 庫,名稱空間允許您透過將名稱附加到程式元素組來將程式碼組織到相關的功能區域。

宣告名稱空間

要將程式碼組織到名稱空間中,必須將名稱空間宣告為檔案中的第一個宣告。然後,整個檔案的內容都成為名稱空間的一部分。

namespace [parent-namespaces.]identifier

以下示例說明了這個概念 -

示例

namespace testing

module testmodule1 =
   let testFunction x y =
      printfn "Values from Module1: %A %A" x y
module testmodule2 =
   let testFunction x y =
      printfn "Values from Module2: %A %A" x y

module usermodule =
   do
      testmodule1.testFunction ( "one", "two", "three" ) 150
      testmodule2.testFunction (seq { for i in 1 .. 10 do yield i * i }) 200

編譯並執行程式後,將產生以下輸出 -

Values from Module1: ("one", "two", "three") 150
Values from Module2: seq [1; 4; 9; 16; ...] 200
廣告

© . All rights reserved.