我正在学习C#,我正在尝试制作游戏而且我遇到了问题.我有两个班,我打电话Item和Weapon,Weapon看起来是这样的:
class Weapon : Item
{
int damage;
int durability;
public void asd()
{
Weapon shortSword = new Weapon();
shortSword.dmg = 5;
shortSword.durability = 20;
Weapon woodenBow = new Weapon();
woodenBow.dmg = 3;
woodenBow.durability = 15;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有另一个包含不同方法的类,当玩家走在一个项目上并且它应该随机化该项时调用其中一个.但是我无法Weapon从其他课程中找到对象.我如何联系他们,或解决这个问题?
您的设计存在问题.创建武器的方法不应该是类的实例方法Weapon.它可能是一个静态方法,或者甚至可能是某个其他类的方法.
你的方法应该在集合中或作为一个集合返回武器IEnumerable.
public class Weapon : Item
{
public int Damage { get; set; }
public int Durability { get; set; }
// Consider moving this method to another class.
public static IEnumerable<Weapon> CreateWeapons()
{
List<Weapon> weapons = new List<Weapon>();
Weapon shortSword = new Weapon { Damage = 5, Durability = 20 };
weapons.Add(shortSword);
Weapon woodenBow = new Weapon { Damage = 3, Durability = 15 };
weapons.Add(woodenBow);
return weapons;
}
}
Run Code Online (Sandbox Code Playgroud)
我还使用了对象初始化器语法来使代码更简洁,并整理了一些方法/属性命名.
| 归档时间: |
|
| 查看次数: |
393 次 |
| 最近记录: |