2014-09-04 219 views
-1

我正在使用自定義應用程序類來存儲我的全局變量,但我似乎無法使其工作。 這裏是我的課:在Xamarin c#中使用自定義應用程序類的全局變量#

#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示例任何文件,這兩個代碼給我的「無法從源轉換爲目標」異常

MyApp m = (MyApp)Application; 

Myapp m=(MyApp)ApplicationContext; 

能不能幫我想出解決辦法? 和我有另一個問題。它是一個很好的做法,使用方法或使用公共靜態獲取或設置變量? 謝謝

回答

0

應用程序是一個類的定義。

您將需要一個應用程序實例來轉換爲MyApp。

使MyApp成爲一個靜態類。

使你的方法的靜態方法。

然後,您可以簡單地訪問替換應用程序與MyApp的所有引用,並以此方式使用它。

+0

有一個名爲應用there.i'm屬性使用,而不是類定義 – 2014-09-04 15:33:39

+0

這是一個靜態類定義,而不是一個屬性。您可以使用靜態類定義的靜態方法和屬性,但它本身不是類Application的實例。 – 2014-09-04 15:38:26

+0

因此,如果我必須在每個活動中製作我的課程的實例,我怎樣才能共享它們之間的變量? – 2014-09-04 15:55:56