Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过单击按钮调用类函数_C#_Winforms - Fatal编程技术网

C# 通过单击按钮调用类函数

C# 通过单击按钮调用类函数,c#,winforms,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.

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

文件: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)。因此,我将一个按钮从工具箱拖放到表单设计器中。双击一下之后,VisualStudio添加了以下代码行

    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文件的public Form1()类之外使用Adventurer。我怎样才能让这个冒险家“公开”?我对这个有点陌生,所以请友好。

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

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(...));
    }

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

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(...));
    }

只需将冒险家公之于众你在哪里申报冒险家?在方法或类中?注释1解决了问题。不知道为什么我自己没想到这个。谢谢只需将冒险家公之于众你在哪里申报冒险家?在方法或类中?注释1解决了问题。不知道为什么我自己没想到这个。谢谢我建议使用属性,而不是公共字段。@Mafii,这是真的,但如果这是OP缺少的,那么它也可能是一个
private
字段。。。请参见回答中的编辑。我建议使用属性,而不是公共字段。@Mafii,这是真的,但如果OP缺少的是属性,那么它也可能是
私有
字段。。。请参见答案中的编辑。