2012-02-01 33 views
0

這是在C#示例代碼:我可以在F#中的類中定義結構嗎?

class exampleClass 
{ 
    struct exampleStruct 
    { 
     public int number; 
    } 

    private exampleStruct[,] e;      
    private enum exampleMove { Up, Down, Right, Left, Enter, Escape }; 
    Stack<int> returnPath; 
    bool returntoBeg; 
    int numRandomMoves; 

    public exampleClass() 
    { 
     e = new exampleStruct[5, 5]; 
     exampleStruct ex; 
     returntoBeg = false; 
     returnPath = new Stack<int>(); 
     numRandomMoves = 0; 

     for (int y = 0; y < 5; y++) 
     { 
      for (int x = 0; x < 5; x++) 
      { 
       ex = new exampleStruct(); 
       ex.number = 0 

       e[x, y] = ex; 
      } 
     } 
    } 
} 

我有一個示例代碼像上面,我想將它翻譯成F#。但問題是,當我使用F#創建一個類並在其中定義結構時,它顯示錯誤並指出我無法在類類型中聲明類型。任何幫助?

+2

爲什麼你需要這樣的功能?只是將C#逐行移植到F#? – pad 2012-02-01 07:14:01

+0

只是想學習如何做:) – 2012-02-01 09:01:00

+1

可能的重複:http://stackoverflow.com/questions/8948332/why-doesnt-f-support-nested-classes – kkm 2012-02-01 11:31:33

回答

2

我認爲以下是嵌套類型的一個很好的解決方法。

namespace MyNamespace 

module private PrivateTypes = 
    [<Struct>] 
    type ExampleStruct(number: int) = 
    member __.Number = number 

open PrivateTypes 

type ExampleClass() = 
    let e = Array2D.init 5 5 (fun y x -> ExampleStruct(0)) 
    //other members 

ExampleStructPrivateTypes,這是唯一在同一文件中可見下嵌套。

1

雖然不能嵌套類型,但可以使用F#提供的內在複雜類型。元組通常是一個很好的數據結構,它的數據結構不是很寬,可觀察的範圍,比如你的情況。

實際上,我通常在一個名爲e的模塊中定義實現類型。 G。內部的,不要讓他們從圖書館逃跑。您也可以爲每個邏輯組類或甚至每個複雜的類實現定義單獨的模塊。

相關問題