使用Application对象存储数据和全局变量 [英] Store data and global variables using the Application object

查看:55
本文介绍了使用Application对象存储数据和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Xamarin中,我想使用Application对象存储数据和全局变量.

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

我在以下资源中查找了以下代码: http://www.helloandroid.com/tutorials/maintaining-global-application-状态

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

这是我的代码:

    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:

名称"GetApplication"在当前上下文中不存在

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

请问有什么帮助可以使此代码正常工作吗?

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

编辑

这是我的代码:

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

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

这是我得到的错误:

异常:System.InvalidCastException:无法从源类型转换为目标类型.

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

我可以帮忙吗?

推荐答案

看看代码,您可以将变量设为公共静态变量.

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

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

用法:

HelloApplication.GlobalVariable = 10;

这篇关于使用Application对象存储数据和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆