整数不是';t由线程c#升级

本文关键字:线程 升级 整数 | 更新日期: 2023-09-27 17:57:57

我在C#中声明了一个静态公共int,然后这个int被它的构造函数中的线程所支持,线程的工作很简单,可以增加它,但它不会发生在这里我声明静态值:

class Global
{
    static public  int hardcap = 100;
    public int speed;
    static public Semaphore myhitpoints = new Semaphore(1, 1);
    static public Semaphore oponenthitpoints = new Semaphore(1, 1);
   static  public int mhp = 100;
    static public int ohp = 100;
    static public int mmana = 0;
    static public int omana = 0;
  public static Charm dragonblade = new   Charm(10, 30, 3, myhitpoints, oponenthitpoints, mhp, ohp, "dragon blade", mmana);
  public  static  Charm dragonshield = new Charm(30, 10, 5, myhitpoints, oponenthitpoints, mhp, ohp, "dragon shield", mmana);
    public static Charm b1charm;
    public static  Charm b2charm;
    public static Opponent enemy;
}
class ManaWell
    {
        int mana_regen;
        int cap = 1000;
        int target;
        public ManaWell(int x, int y)
        {
           mana_regen = x;
            target = y;
        }
        public void Refill()
        {
            while (true)
            {
               // if (this.target + mana_regen <= cap)
                if (target+mana_regen<cap)
                {
                    Thread.Sleep(3000);
                    target += mana_regen;
                    MessageBox.Show(target.ToString());
                }
            }
        }
    }
 ManaWell mw1 = new ManaWell(20,Global.mmana);
        ManaWell mw2 = new ManaWell(20,Global.omana);
        Thread tmw1 = new Thread(new ThreadStart(mw1.Refill));
        Thread tmw2 = new Thread(new ThreadStart(mw2.Refill));
        tmw1.Start();
        tmw2.Start();

所以target很好,但y不会增加。

整数不是';t由线程c#升级

Integer作为值传递,并使局部增加。它不会增加你在中传递的静态变量

价值与参考类型

如果希望更新外部静态变量,可以使用ref关键字。

除此之外,您应该在从多个线程访问变量时同步对该变量的访问。。。

如果您有应该存储并稍后调用的"目标",则应该将一个委托(指向update方法)传递给构造函数。这个代理您可以存储并稍后调用

当您创建ManaWell对象并传入变量时,它将仅是分配给目标的变量值。所以,当你添加到目标时,你只做了那个;传入的变量不会受到影响(如您所见)

如果你真的在传递一个公共静态int,那么要增加它,只需直接对它进行数学运算(你甚至不必传递它):

MyClass.MyStaticInt += aNumber;

原因是变量的值被传递给构造函数。您只是在增加类的局部变量。