*编辑* ::我在收集实际代码时发现了问题。
我正在Visual Studio 2015中使用C#
我无法传递具有类型为class object的字段的类对象。我创建了两个简单的类,即A类和B类,并且A类中有一个类型为B类的字段。创建了A类的实例,然后将其类型为B类的字段设置为B类的新实例后,似乎工作正常。但是,当我将类A的实例传递给方法时,类型B的字段显示为Null。我可以编写所有B类字段的值,并且它们在调试之前会在进入方法之前显示正确的值,但是当将A类对象传递给方法时,它将引发NullReferenceException并告诉我“对象引用未设置为实例”一个物体。”我的A类对象中的所有其他字段都可以正常工作; B类类型的字段是唯一执行此操作的字段。
当我将方法复制/粘贴到新的解决方案并进行修剪/添加以消除所有错误时,它可以正常工作。因此,我不确定为什么我的程序会一直以这种方式失败。
有什么建议吗?
class Program
{
// Start of the program
static void Main(string[] args)
{
// Instantiate the player
Player player = new Player() { playerWeapon = new Weapon() };
showPlayerStats(player);
}
// Method shows the player's stats
static void showPlayerStats(Player player)
{
Console.WriteLine(" ******** Player Statistics ********");
Console.WriteLine();
Console.WriteLine(" Player Name:".PadRight(16) + player.playerName);
Console.WriteLine(" Player Gender:".PadRight(16) + player.playerGender);
Console.WriteLine(" Player Race:".PadRight(16) + player.playerRace);
Console.WriteLine(" Player Class:".PadRight(16) + player.playerClass);
Console.WriteLine(" Player Health:".PadRight(16) + player.playerHealth + "/" + player.playerMaxHealth);
Console.WriteLine(" Player EXP:".PadRight(16) + player.playerEXP);
Console.WriteLine(" Player Gold:".PadRight(16) + player.playerMoney);
Console.WriteLine(" Player Weapon:".PadRight(16) + player.playerWeapon.name);
Console.ReadLine();
}
// Create player with random attributes
static Player RandomPlayer()
{
Player player = new Player(); //<<== This is where I goofed
return player;
}
}
class Player
{
public string playerName = "Name";
public string playerGender = "Gender";
public string playerRace = "Race";
public string playerClass = "Class";
public int playerHealth = 100;
public int playerEXP = 0;
public int playerMaxHealth = 100;
public int playerMoney = 50;
public double playerOneHanded = 1;
public double playerTwoHanded = 1;
public double playerRanged = 1;
public double playerMagic = 1;
public Weapon playerWeapon;
}
class Weapon
{
public string name = "Knife";
public int damage = 6;
public string type = "One";
}
答案 0 :(得分:0)
当我回顾代码以收集实际片段时,发现了问题。我在测试游戏时使用的是随机角色创建过程,而忽略了在返回玩家的方法之后将Weapon放到Player.playerWeapon字段中,因此使用了带有Null字段的Player对象的新实例。感谢您的协助。