c# - Visual Studio Form 上的错误“对象引用未设置为实例等”
问题描述
所以这是一个使用表格的“游戏”。但是我的对象出现错误,我不确定我到底是为什么。我有以下 2 个课程:玩家和武器。我试图让 player.Attack() 的结果显示为字符串,但是当我单击表单上的按钮时,它给了我可爱的“对象引用未设置为对象的实例”错误。我试过 Convert.ToString(player.Attack()); 还尝试了 String.Format(player.Attack()),甚至设置了一个字符串变量来转换为字符串,但我一直收到这个错误。我只希望方法的结果在我的表单标签上显示为字符串。
这是 PLAYER 类
public class Player
{
private Form1 Login { get; set; }
private Weapon sword;
public string PlayerName { get; set; }
public int Health { get; set; } = 36;
public int Strength { get; set; } = 6;
public Player(string playername, int health, int strength, Weapon s)
{
this.Login.UserName = playername; //gets character name from form1 and makes it the username throughout the game.
// this.PlayerName = playername;
this.Health = health;
this.Strength = strength;
this.sword = s;
}
public int Attack()
{
return sword.Attack(this.Strength);
}
这是武器类
public class Weapon
{
public string Name { get; set; } = "Hel Fire";
public int AtkDmg { get; set; } = 4;
public Weapon(string name, int attack)
{
this.Name = name;
this.AtkDmg = attack;
}
//Attack function that will take users STR and Sword Strength
public int Attack(int strength)
{
int result = strength + this.AtkDmg; // AtkDmg is the weapons Strength
return result;
}
这是 button_click 对象所在的表单。
private void AtkSword_Click(object sender, EventArgs e)
{
int GoblinHealth = 36;
int GoblinAttack = 2;
if (GoblinHealth != 0)
{
GoblinHealth -= player.Attack();
player.Health -= GoblinAttack;
}
//below should display text and results from attack
ResultsLabel.Text = Format.ToString("{0} Attacks the goblin. The goblin is at {1} HP. \n {2} is at {3} HP", player.PlayerName, GoblinHealth, player.PlayerName, player.Health);
}
解决方案
我认为问题出在这里:
ResultsLabel.Text = Format.ToString("{0} Attacks the goblin. The goblin is at {1} HP. \n {2} is at {3} HP", **player.PlayerName**, GoblinHealth, **player.PlayerName**, player.Health);
您正在设置变量this.Login.UserName而不是Player.Playername。稍后您尝试访问它并且它不存在。你应该设置:
public Player(string playername, int health, int strength, Weapon s)
{
this.Playername = playername //here
this.Health = health;
this.Strength = strength;
this.sword = s;
}
或使用登录用户名
ResultsLabel.Text = Format.ToString("{0} Attacks the goblin. The goblin is at {1} HP. \n {2} is at {3} HP", this.Login.UserName, GoblinHealth, this.Login.UserName, player.Health);
推荐阅读
- mongodb - Mongodb $elemMatch 获取匹配空数组的文档
- c++ - 无法在 Visual Studio 2019 中打开文件
- scala - 使用空格拆分文件,其中列数据也有空格
- javascript - 如何使用 Visual Studio CE 2019 缩小、捆绑然后发布 TypeScript/React 单页 Web 应用程序项目
- javascript - 不能将 Stripe 与 nuxt 和 typescript 一起使用
- r - R中带有beta家族的gam()的随机效应
- android - 我如何读取特定用户的相关数据
- php - codeigniter中的验证rest api保持返回false
- java - 在 JAX-RS 中使用 Json:禁止空值
- java - AssertJ JSON 属性检查