c# - 如何在不直接创建实例的情况下选择实例应具有的名称?
问题描述
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# 的初学者,所以请以我能理解的方式向我解释。我试图到处寻找这个解决方案,但没有找到。如果有任何缺少解决问题所必需的代码,我会在需要时将其发布在这里。
解决方案
伙计们,我设法通过为武器装备它的名字而不是它的“标识符”(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!");
}
}
推荐阅读
- html - 图像周围出现奇怪的边框
- r - 使用 transpose 和 group_split 在 excel 中解析数据
- rabbitmq - Logstash 无法连接到我的 RabbitMQ 代理
- javascript - 我不能用 vue.js 上传页面,我哪里出错了?
- python - 在数据类中声明默认值时使用 self
- javascript - 是什么导致了这个 Vue.js 应用程序中的重复键错误?
- android - 获取“无法获取带有结果代码的新注册令牌:0。这绝不应该在设备所有者模式下发生。” 注册设备时
- bash - Bash 从 .txt 字符串中删除特定内容
- powershell - 通过 Powershell 将 AD 组添加到大型公共驱动器
- python - 如何为列表中的每个句子而不是整个列表创建嵌入?