【发布时间】:2021-04-11 17:01:50
【问题描述】:
我正在学习编码。我开始了一个小项目,我设计了一个基于文本的 RPG。 我正在努力在数组中存储和检索对象。 请看看我到目前为止的进展,并告诉我我做错了什么。 如果我使用了错误的方法,请让我知道如何更聪明地做这件事:)
首先我定义了播放器的一些属性:
static class Globals
{
public static string playername;
...
public static object[] playerInventory = new object[4];
}
然后我创建了武器类:
public class Weapon
{
public string weaponName;
public int weaponBaseDamage;
public Weapon(string name, int baseDamage)
{
weaponName = name;
weaponBaseDamage = baseDamage;
}
然后我创建了第一个基本武器并尝试将它存储在一个数组中。
public class Program
{
public static void Main()
{
Weapon StartSword = new Weapon("My first Sword", 1);
Globals.playerInventory[0] = StartSword;
Console.WriteLine(StartSword.weaponName); // This works
Console.WriteLine(Globals.playerInventory[0]); // This prints "CSharp_Shell.Weapon", but I expected "StartSword"
Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
第二个 WriteLine 命令的意外结果告诉我一定有什么地方很不对劲,但我不知道它是什么以及如何修复它。欢迎任何建议! (请记住,我是 Coding 新手)。
【问题讨论】:
-
所有库存物品都是武器吗?
-
对象没有名为“weaponName”的属性/字段,因此它不是类型有效的。使用通用集合(如果需要,可以使用接口)和/或 as/is 运算符。第一个 WriteLine 有效,因为它接受一个对象类型的表达式,并且所有对象都有一个 ToString() 方法。见docs.microsoft.com/en-us/dotnet/standard/generics/collections
-
当你打印一个对象时,它会打印出对象的类型,在你的例子中,类是
Weapon加上一个前缀。参考Console.WriteLine(Globals.playerInventory[0]); -
您必须先投射 Globals.playerInventory[0] 才能访问其属性