单击按钮调用类功能

时间:2017-05-03 12:01:12

标签: c# winforms

我尝试在按钮单击事件中使用类。

文件:Character.cs

public class Character
{
    public Character(string name, int health, int weight, int gold, Inventory inventory)
    {
        this.Name = name;
        this.Health = health;
        this.Weight = weight;
        this.Gold = gold;
        this.Inventory = inventory;
    }

    public string Name;
    public int Health;
    public int Gold;
    public int Weight;
    public Inventory Inventory;
}

我在 Form1.cs文件中创建了一个字符。

Character Adventurer = new Character("Geralt von Riva", 100, 50, 5, new Inventory(new Weapon(1, "Needle", 5, 5, 15, 0), new Armor(2, "Jerkin", 3, 11, 5), new Potion(3, "Little Healhy", 2, 0, 20)));

这很好用。现在,我想在表单中添加一个按钮(在这里名为button1)。所以我将工具箱中的一个按钮拖放到表单设计器中。经过一番双击后,visual studio添加了这行代码

    private void button1_Click(object sender, EventArgs e)
    {
        // here i would like to do something like this:
        Adventurer.Inventory.WeaponList.Add(new Weapon(...));
    }

问题是,我不能在Form1.cs文件的公共Form1()类之外使用Adventurer。我如何让这个冒险家“公开”?我对此有点新意,所以请善待。

1 个答案:

答案 0 :(得分:2)

为了能够访问实例,您应该在全局范围内声明变量,如

public Form1 : Form
{
  private Character Adventurer = null;
  public Form1()
  {
      Adventurer = new Character(.....); 
  }
    private void button1_Click(object sender, EventArgs e)
    {
        // here i would like to do something like this:
        Adventurer.Inventory.WeaponList.Add(new Weapon(...));
    }