首页 > 解决方案 > 如何在不直接创建实例的情况下选择实例应具有的名称?

问题描述

EquipWeapon()当我遇到这个问题时,我正在尝试创建一个基本的 RPG 游戏,当我创建 a 的实例Weapon而不为其分配“名称”/“标识符”时,如何决定应该在函数的参数中放入什么:

    public static void CreateWeapon( string name, int attack, int defense)
    {
        Weapon created_weapon = new Weapon(name, attack, defense);
        weapon_list.Add(created_weapon);
    }

那是在“Weapon”类中,而这是在“Player”类中,在另一个文件中。

    public static void EquipWeapon(Weapon weapon)
    {
        Console.WriteLine("Stats:");
        Weapon.CompareWeaponStats(weapon, Player.equipped_weapon);
        Console.WriteLine("Are you sure you want to equip this weapon?") ;
        if (QuestionPrompt() == true)
        {
            Console.WriteLine("Equipped weapon!");
            ChangeWeapon(weapon);
        }
        else
        {
            Console.WriteLine("You will continue with the same weapon, the new one was discarded.");
        }
    }

此外,是否有更简单的方法将新创建的实例添加到列表中weapon_list,并能够通过武器“代码”或“名称”访问它?

我是 C# 的初学者,所以请以我能理解的方式向我解释。我试图到处寻找这个解决方案,但没有找到。如果有任何缺少解决问题所必需的代码,我会在需要时将其发布在这里。

标签: c#listobject

解决方案


伙计们,我设法通过为武器装备它的名字而不是它的“标识符”(idk它是怎么称呼的)来解决这个问题。

        public static void EquipWeapon(string weapon_name)
        {
            Weapon weapon_to_equip = new Weapon("Test Weapon", 0, 0);

            bool WeaponExists()
            {
                foreach (Weapon weapon in Weapon.weapon_list)
                {
                    if (weapon.name == weapon_name)
                    {
                        weapon_to_equip = weapon;
                        return true;
                    }
                    else
                    {
                        continue;
                    }
                }
                return false;
            }

            if (WeaponExists())
            {
                Console.WriteLine("Stats:");
                Weapon.CompareWeaponStats(weapon_to_equip, Player.equipped_weapon);
                Console.WriteLine("Are you sure you want to equip this weapon?");
                if (QuestionPrompt() == true)
                {
                    Console.WriteLine("You equipped the weapon!");
                    ChangeWeapon(weapon_to_equip);
                }
                else
                {
                    Console.WriteLine("You will continue with the same weapon, the new one was discarded.");
                }
            }
            else
            {
                Console.WriteLine("The weapon you want to equip doesn't exist!");
            }
        }

推荐阅读