如何使用C#方法外部实例化的变量? [关闭]

问题描述 投票:-2回答:1

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

到目前为止是我的代码:

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个回答
4
投票

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

    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
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.