对不起,我不知道我的问题如何表达,
我在C#中有一些代码:
public class Cell
{
public bool boo;
public bool boo2;
public int xPos;
public int yPos;
public Cell(int xPosition, int yPosition)
{
xPos = xPosition;
yPos = yPosition;
}
public void SomeMethod()
{
boo = false;
boo2 = true;
}
public void SomeMethod2()
{
boo = true;
boo2 = false;
}
}
我创建了一个这样的实例:
public static Cell[,] w;
public Cell c
w = new Cell[5,5]
...
//some other code
以上代码的结果是我可以从Cell Class访问方法和属性,我尝试在F#中创建相同的代码
type Cell(xPosition:int,yPosition:int) =
let mutable m_boo = false
let mutable m_boo2 = false
//x and y position of cell in picture box
let mutable xPosition = 0
let mutable yPosition = 0
new(xPosition,yPosition) = new Cell(xPosition,yPosition)
new() = new Cell(0,0)
member this.xPos with get() = xPosition
and set newX = xPosition <- newX
member this.yPos with get() = yPosition
and set newY = yPosition <- newY
member this.boo with get() = m_boo
and set newBoo = m_boo <- newBoo
member this.boo2 with get() = m_boo2
and set newBoo2 = m_boo2 <- newBoo2
member this.SomeMethod() =
this.boo <- false
this.boo2 <- true
member this.SomeMethod2() =
this.boo <- true
this.boo2 <- false
我尝试创建实例:
let worldGrid:Cell[,] = Array2D.zeroCreate 5 5
worldGrid.[0,0].SomeMethod2()
编译代码的结果是:
System.NullReferenceException:未将对象引用设置为对象的实例
在我的代码中是不正确的,还是我做错了?希望阅读代码有助于理解我的问题。
答案 0 :(得分:2)
Array2D.zeroCreate 5 5
确实创建了25个Cell
类的空实例。如果要使用默认值初始化它们,则应使用:
let worldGrid = Array2D.init 5 5 (fun _ _ -> Cell())
否则您必须在访问其方法和字段之前将矩阵的每个元素分配给Cell
实例。
另一个问题是可变值xPosition
和yPosition
被初始化为0
有关构造函数的参数。此外,这些可变值和类的参数应具有不同的名称,以避免阴影和混淆。该课程可能如下所示:
type Cell(xPos:int, yPos:int) =
let mutable m_boo = false
let mutable m_boo2 = false
// x and y position of cell in picture box
let mutable xPosition = xPos
let mutable yPosition = yPos
// ...