【问题标题】:How to use a variable instantiated outside a method in C#? [closed]如何使用在 C# 中的方法之外实例化的变量? [关闭]
【发布时间】:2020-04-13 10:42:34
【问题描述】:

我想知道如何在稍后的方法中使用全局变量——我已经将它实例化为公共整数类型。

到目前为止,这是我的代码:

public int money = 500000;
//other variables

//...some code in between

public static void UpdateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
        {
            //   \/ Problem here
            if (money < cost)
            {
                //uncheck box
            }
            else
            {
                //implement input variables with other external variables
            }
        }

【问题讨论】:

  • 也让它成为静态的。

标签: c# variables methods public


【解决方案1】:

从您的方法中删除“静态”关键字,静态方法无法访问实例变量。静态方法属于类型本身,而您的实例变量不属于。另一种选择是将“钱”设为静态,但您的所有实例都将使用相同的“钱”,这可能不是您的目标。

    public void updateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
    {
        //   v- No more Problem here :)
        if (money < cost)
        {
            //uncheck box
        }
        else
        {
            //implement input variables with other external variables
        }
    }

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多