Store data and global variables using the Application object

回眸只為那壹抹淺笑 提交于 2021-01-27 16:45:33

问题


In Xamarin, I am wanting to store data and global variables using the Application object.

I looked at this resource for this code: http://www.helloandroid.com/tutorials/maintaining-global-application-state

Here is my code:

    public class HelloApplication : Application 
    {
        private int GlobalVariable = 1;

        public int GetGlobalVariable()
        {
            return GlobalVariable;
        }

        public void SetGlobalVariable(int GlobalVariable)
        {
            this.GlobalVariable = GlobalVariable;
        }
    }

I am trying to reference the class using this code:

    ((HelloApplication)GetApplication()).setGlobalVariable(10);
    int variable=((HelloApplication)GetApplication()).getGlobalVariable();

When I build the application I am getting this error for both the above lines of code:

The name 'GetApplication' does not exist in the current context

Can I please have some help to get this code working?

EDIT

Here is my code:

HelloApplication state = ((HelloApplication) this.ApplicationContext);
state.SetGlobalVariable(10);
int globalVariable = state.GetGlobalVariable ();

Toast.MakeText (this, "Global variable " + globalVariable, ToastLength.Short).Show ();

This is the error I am getting:

UNHANDLED EXCEPTION: System.InvalidCastException: Cannot cast from source type to destination type.

Can I please have some help to get this working?


回答1:


Looking at the code you could just make the variable a public static.

public class HelloApplication : Application 
{
    public static int GlobalVariable = 1;
}

Usage:

HelloApplication.GlobalVariable = 10;



回答2:


change:

((HelloApplication)GetApplication())

to

((HelloApplication)GetApplicationContext())


来源:https://stackoverflow.com/questions/21494238/store-data-and-global-variables-using-the-application-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!