[英]C# Reaching objects from a different class
I'm learning C# and I'm trying to make a game and I have a problem. 我正在学习C#,正在尝试制作游戏,但遇到了问题。 I have two classes that I call
Item
and Weapon
, Weapon
looks something like this: 我有两个类,分别称为
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;
}
}
Then I have another class containing different methods, one of them is called when the player walks on an item and its supposed to randomize that item. 然后,我有另一个包含不同方法的类,当玩家在某物品上行走时应该调用其中的一种方法,并且应该使该物品随机化。 But I can't reach the objects in
Weapon
from this other class. 但是我无法从其他班级接触到
Weapon
的物体。 How do I reach them, or solve this problem? 我如何联系他们,或解决这个问题?
There is a problem with your design. 您的设计有问题。 The method that creates weapons shouldn't be an instance method on the
Weapon
class. 创建武器的方法不应是
Weapon
类的实例方法。 It could perhaps be a static method, or perhaps even a method on some other class. 它可能是静态方法,甚至可能是其他类上的方法。
Your method should return the weapons in a collection or as an IEnumerable
. 您的方法应该以集合或
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;
}
}
I also used the object initializer syntax to make the code more concise, and tidied up some of your method/property naming. 我还使用对象初始化程序语法使代码更简洁,并整理了一些方法/属性命名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.