在Xamarin c#中为全局变量使用自定义应用程序类

时间:2014-09-04 15:02:03

标签: c# android xamarin

我使用自定义应用程序类来存储我的全局变量,但我似乎无法让它工作。 这是我的班级:

    #if DEBUG
    [assembly: Application(Debuggable = true)]
    #else
    [assembly: Application(Debuggable=false)]
    #endif
    internal class MyApp : Application
    {

        private Customer loginedCustomer;
        private List<string> sefareshItems;
        public Boolean isOnline { set; get; }
        public MyApp(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)
        {
        }
        public override void OnCreate()
        {
            // If OnCreate is overridden, the overridden c'tor will also be called.
            base.OnCreate();
        }

        public void SetLCustomer(Customer customer)
        {
            loginedCustomer = customer;
        }

        public Customer GetLCustomer()
        {
            return loginedCustomer;
        }

        public void SetItems(List<string> items)
        {
            sefareshItems = items;
        }

        public List<string> GetItems()
        {
            return sefareshItems;
        } 

    }

因为我可以找到关于使用这样的类的任何文档,并且通过查看java示例,这两个代码都给了我&#34;无法从源转换为目标&#34;例外

 MyApp m = (MyApp)Application;

Myapp m=(MyApp)ApplicationContext;
你可以帮我解决这个问题吗? 我有另一个问题。使用方法或使用公共静态方法获取或设置变量是一个好习惯吗? 谢谢

1 个答案:

答案 0 :(得分:0)

应用程序是类定义。

您需要将一个Application实例转换为MyApp。

使MyApp成为静态类。

制作方法的静态方法。

然后,您只需访问用MyApp替换所有对Application的引用,并以这种方式使用它。

相关问题