gpt4 book ai didi

C# 从类中获取值到 mainForm

转载 作者:太空宇宙 更新时间:2023-11-03 23:05:26 25 4
gpt4 key购买 nike

我有以下类(class):

    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. 私有(private) BaseWeapon newWeapon;当您将变量声明为私有(private) 时,CreateNewWeapon 类之外的任何对象都无法访问它。
  2. public void CreateWeapon() 您的方法的返回值为 void。您应该将其更改为 BaseWeapon 并将 newWeapon 返回给调用者

我认为您应该将代码更改为:

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

关于C# 从类中获取值到 mainForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41368818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com