【问题标题】:Using a Public Integer Variable as a Counter C#使用公共整数变量作为计数器 C#
【发布时间】:2017-09-16 12:41:18
【问题描述】:

我正在 Visual Studio 中创建一个口袋妖怪类型的游戏。我现在正在处理库存表格。

我的问题是我可以使用公共计数变量来跟踪库存吗?

设置:

public int healthPotionCount = 0;

如果玩家遇到健康药水会增加它的价值

if(picPlayer.Bounds.IntersectsWith(hPotion.Bounds)
      {
          healthPotionCount++;
      }

最终使用同一个公共变量来确定是否在清单中显示:

if(healthPotionCount > 0)
   {
       picBox.BackgroundImage = (the health potion image);
       lblQuantity.Text = ""+healthPotionCount; 
   }

有了这个,我的问题是我的解决方案中有很多表单,我希望所有表单都可以访问这个变量。这个逻辑是不是太笨拙了?

【问题讨论】:

    标签: c# variables logic counter public


    【解决方案1】:

    有了这个,我的问题是我的解决方案中有很多表格 我希望这个变量可以被所有形式访问。

    您可以将其设为static,这意味着它属于类而不是特定的表单对象,因此您可以在多个表单中访问它。

    public static int healthPotionCount { get; set;}
    

    【讨论】:

    • 嗨,所以在我的 GlobalVariable 类中它显示为:class healthPotion { public static int healthPotionCount = 0;但我仍然无法使用 MessageBox.Show(" " +healthPotionCount); 将其称为另一种形式;
    • @Tarheel81 为了以另一种形式访问它,您需要指定表单的名称,然后是变量,即如果您想从 form2 访问它,您可以使用Form1.healthPotionCount
    • @Tarheel81hi,我是新人,但我想的是为什么不在全局变量 Class 中使用 get setstackoverflow.com/questions/5096926/…
    • @chopperfield 上面的示例与同时使用get/set 没有什么不同,但是,您可以使用它。查看更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2011-12-05
    • 2020-01-31
    • 1970-01-01
    相关资源
    最近更新 更多