[英]C# get value from class into mainForm
我有以下課程:
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;
}
但是這些值甚至都不會轉移到第一個表單,它們在哪里丟失?
您的代碼存在多個問題:
我認為您應該將代碼更改為此:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.