简体   繁体   English

使用Application对象存储数据和全局变量

[英]Store data and global variables using the Application object

In Xamarin, I am wanting to store data and global variables using the Application object. 在Xamarin中,我想使用Application对象存储数据和全局变量。

I looked at this resource for this code: http://www.helloandroid.com/tutorials/maintaining-global-application-state 我查看了这个代码的资源: 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 当前上下文中不存在名称“GetApplication”

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. UNHANDLED EXCEPTION:System.InvalidCastException:无法从源类型转换为目标类型。

Can I please have some help to get this working? 我可以帮忙解决这个问题吗?

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;

change: 更改:

((HelloApplication)GetApplication())

to

((HelloApplication)GetApplicationContext())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM