C#从类中获取值到mainForm中

时间:2016-12-28 19:52:43

标签: c# forms class oop

我有以下课程:

    public class CreateNewWeapon : BaseWeapon
{

    string[] weaponNames = { "Dragonslayer", "SoopaDoopa", "Mastersword" };

    private BaseWeapon newWeapon;

    public void CreateWeapon()
    {

        Random rnd = new Random();
        int x = rnd.Next(0, weaponNames.Length);

        newWeapon = new BaseWeapon();

        newWeapon.ItemName = weaponNames[x];
        newWeapon.Strength = rnd.Next(0, 5);
        newWeapon.Vitality = rnd.Next(0, 5);
        newWeapon.Intelligence = rnd.Next(0, 5);
    }

}

并希望以我的主要形式获取值,以第二种形式设置标签:

        private void button2_Click(object sender, EventArgs e)
    {

        newWep = new Items.CreateNewWeapon();

        newWep.CreateWeapon();

        ShowWeapon shWep = new ShowWeapon();

        shWep.Label6 = newWep.Strength.ToString();
        shWep.Visible = true;
    }

但这些价值观甚至不会转移到第一张表格中,他们会在哪里丢失?

1 个答案:

答案 0 :(得分:3)

您的代码存在多个问题:

  1. 私人BaseWeapon newWeapon; 当您将变量声明为 private 时, CreateNewWeapon 类之外的任何对象都无法访问该变量。
  2. public void CreateWeapon()您的方法的返回值为void。您应该将其更改为 BaseWeapon 并将 newWeapon 返回给调用者
  3. 我认为您应该将代码更改为:

    public class CreateNewWeapon : BaseWeapon
    {
    
        string[] weaponNames = { "Dragonslayer", "SoopaDoopa", "Mastersword" };
    
        public BaseWeapon CreateWeapon()
        {
    
            Random rnd = new Random();
            int x = rnd.Next(0, weaponNames.Length);
    
            var newWeapon = new BaseWeapon();
    
            newWeapon.ItemName = weaponNames[x];
            newWeapon.Strength = rnd.Next(0, 5);
            newWeapon.Vitality = rnd.Next(0, 5);
            newWeapon.Intelligence = rnd.Next(0, 5);
    
            return newWeapon;
        }
    
    }
    

    并在button2_Click方法中,以这种方式调用它:

    var weapon = newWep.CreateWeapon();