【问题标题】:How can I store an Object in an Array? [duplicate]如何将对象存储在数组中? [复制]
【发布时间】: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] 才能访问其属性

标签: c# arrays object


【解决方案1】:

这是必需的类型转换。请尝试如下:

Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName)

【讨论】:

    【解决方案2】:

    好的,让我们看看你的代码做了什么:

    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"
    

    在这里你尝试写一个对象。但是对象不是字符串,因此 c# 会自动尝试将其转换为字符串并查看类型。所以预计它不会写属性而是类型的表示。

    Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
    

    Globals.playerInventory 被定义为object[] playerInventory,所以即使我们知道您在那里输入了武器类型的对象,我们也需要指定它。通过让 playerInventory 为 Weapon[] playerInventory 类型,或者在使用其属性之前对对象进行类型转换,如下所示:

    Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName);
    

    【讨论】:

      猜你喜欢
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2021-10-15
      • 2011-11-11
      • 2021-08-27
      • 2016-03-26
      相关资源
      最近更新 更多