gpt4 book ai didi

c# - 为什么在尝试调用我的方法时会出现对象引用错误?

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:40 25 4
gpt4 key购买 nike

对于这段代码,当我尝试调用 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);
}

如果需要,将在页面上刷新以提供更多信息。

编辑这是该方法引用的方形类库(省略了变量):

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) { }

}

最佳答案

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);
...
}

关于c# - 为什么在尝试调用我的方法时会出现对象引用错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com