2011-11-14 19 views
5

tengo código como este en C#:conversión de C# struct a F #

namespace WumpusWorld 
    { 
     class PlayerAI 
     { 
      //struct that simulates a cell in the AI replication of World Grid 
      struct cellCharacteristics 
      { 
       public int pitPercentage; 
       public int wumpusPercentage; 
       public bool isPit; 
       public bool neighborsMarked; 
       public int numTimesvisited; 
      } 

      private cellCharacteristics[,] AIGrid;     //array that simulates World Grid for the AI 
      private enum Move { Up, Down, Right, Left, Enter, Escape }; //enum that represents integers that trigger movement in WumpusWorldForm class 
      Stack<int> returnPath;          //keeps track of each move of AI to trace its path back 
      bool returntoBeg;           //flag that is triggered when AI finds gold 
      int numRandomMoves;           //keeps track of the number of random moves that are done 

      public PlayerAI() 
      { 
       AIGrid = new cellCharacteristics[5, 5]; 
       cellCharacteristics c; 
       returntoBeg = false; 
       returnPath = new Stack<int>(); 
       numRandomMoves = 0; 

       for (int y = 0; y < 5; y++) 
       { 
        for (int x = 0; x < 5; x++) 
        { 
         c = new cellCharacteristics(); 
         c.isPit = false; 
         c.neighborsMarked = false; 
         c.numTimesvisited = 0; 

         AIGrid[x, y] = c; 
        } 
       } 
      } 
     } 
    } 

no sé cómo convertir esto en C# struct de C# y poner en práctica el struct en una matriz como mi código de seguridad.

+1

¿Por qué no usas esa estructura C# de F #? ¿Con qué tienes exactamente problemas? ¿Qué has intentado? Por cierto, las estructuras mutables son malas y no deberías usarlas a menos que sea realmente necesario. – svick

+0

es solo una pequeña parte de mi código, esa estructura está dentro de una clase, y la clase tiene métodos que usan la estructura como Array. Intento convertir mi clase C# en clase F #. Agregué más código en mi código de ejemplo –

Respuesta

10

Puede definir una estructura usando la palabra clave struct (como muestra Stilgar) o usando el atributo Struct, que se ve así. También he añadido un constructor que inicializa la estructura:

[<Struct>] 
type CellCharacteristics = 
    val mutable p : int 
    val mutable w : int 
    val mutable i : bool 
    val mutable ne : bool 
    val mutable nu : int 

    new(_p,_w,_i,_ne,_nu) = 
    { p = _p; w = _w; i = _i; ne = _ne; nu = _nu } 

// This is how you create an array of structures and mutate it 
let arr = [| CellCharacteristics(1,2,true,false,3) |] 
arr.[0].nu <- 42 // Fields are public by default 

Sin embargo, en general no se recomienda el uso de tipos de valores mutables. Esto causa un comportamiento confuso y el código es bastante difícil de razonar. Esto se desalienta no solo en F #, sino incluso en C# y .NET en general. En F #, la creación de una estructura inmutable es también más fácil:

// The fields of the strcuct are specified as part of the constructor 
// and are stored in automatically created (private) fileds 
[<Struct>] 
type CellCharacteristics(p:int, w:int, i:bool, ne:bool, nu:int) = 
    // Expose fields as properties with a getter 
    member x.P = p 
    member x.W = w 
    member x.I = i 
    member x.Ne = ne 
    member x.Nu = nu 

Al utilizar estructuras inmutables, que no será capaz de modificar los campos individuales de la estructura. En su lugar, deberá reemplazar todo el valor de la estructura en la matriz. Normalmente puede implementar el cálculo como miembro de la estructura (digamos Foo) y luego simplemente escriba arr.[0] <- arr.[0].Foo() para realizar la actualización.

+0

que entiendo de su código, pero aún no lo entiendo cuando quiero implementarlo en mi código. En mi código, la estructura está en una clase, y en C# puedo implementar la estructura en una matriz fácilmente. No puedo explicar esto mejor, porque mi inglés no es bueno. Si no te importa, echa un vistazo a este enlace: http://stackoverflow.com/questions/8126680/need-help-to-convert-my-homework-from-c-sharp-to-f –

+0

oh, perdón , parece que violé las reglas, entonces el enlace está cerrado –