当我尝试调用我的方法时,为什么会出现对象引用错误?

时间:2015-10-26 08:37:54

标签: c# winforms

对于这段代码,当我尝试拨打Square.EffectOnPlayer(player);时出现错误 该错误表示需要对象引用,为什么不接受player

public void  Move(int numberOfSquares, Player player) {
    int current_pos;
    int new_pos;

    current_pos = Square.GetSquarenumber(location);
    new_pos = numberOfSquares + current_pos;

    location = Board.GetGameBoardSquare(new_pos);

    Square.EffectOnPlayer(player);
}
如果需要,

将刷新页面以提供更多信息。

EDIT 这是方法引用的方形类库(变量遗漏):

public class Win_Square : Square
{
    public Win_Square(string n,int nu)

    {
        Name = n;
        number = nu;
    }

    public override void EffectOnPlayer(Player who)
    {
        who.Add(add);
    }
}

public class Lose_Square : Square
{
    public Lose_Square(string n,int nu)
    {
        Name = n;
        number = nu;
    }

    public override void EffectOnPlayer(Player who)
    {
        who.Deduct(deduct);
    }  
}

public class Chance_Square : Square
{
    public Chance_Square(string n,int nu)
    {
        Name = n;
        number = nu;
    }

    public override void EffectOnPlayer(Player who)
    {
        Random rand = new Random();

        if (rand.Next(0, 2) == 0)
            who.Deduct(one_hundred);
        else
            who.Add(one_hundred);
    }
}

public static int GetSquarenumber(Square square)
{
    int n = 0;
    string name;
    name = square.Name;

    if (name == "Finish")
    {
        n = 55;
    }
    if (name == "Start")
    {
        n = 0;
    }
    else 
    {
        n = Int32.Parse(name);
    }
    return n;
}

public virtual void EffectOnPlayer(Player who) { }

}

1 个答案:

答案 0 :(得分:3)

public override void EffectOnPlayer(Player who)
{
    Random rand = new Random();

    if (rand.Next(0, 2) == 0)
        who.Deduct(one_hundred);
    else
        who.Add(one_hundred);
}

此函数不是静态,而其他函数调用EffectOnPlayer而不引用Square类的实例将导致错误。因此,您需要引用Square实例或将其设置为静态。

如果你只是给一个方形实例赋予Move函数,那么一切都应该没问题。

public void  Move(int numberOfSquares, Player player, Square square)
{
     square.EffectOnPlayer(player);
     ...
}