簡體   English   中英

App class 中的公共變量無法在其他 class xamarin.forms 中引用

[英]public variable in App class can't get referenced in other class xamarin forms

我有這個作為我的App.xaml.cs

using System;
using System.Collections.Generic;
using Xamarin.Forms;
using System.Threading.Tasks;
using Xamarin.Forms.Xaml;
using Newtonsoft.Json;
using System.Net.Http;

namespace MyShop
{
    public partial class App : Application
    {
        public string productsJSON = {{very large string}};
        public List<Product> jsonDataCollection = new List<Product>();
        public App()
        {
            InitializeComponent();
            
            jsonDataCollection = JsonConvert.DeserializeObject<List<Product>>(productsJSON);
            foreach (Product p in jsonDataCollection)
            { 
                Application.Current.Properties[p.Id] = 0;
            }

            MainPage = new NavigationPage(new Page1());
        }
 ...

在我的ProductsPage.xaml.cs中,我想引用公共變量productsJSON所以我稱它為App.productsJSON並分配給一個字符串變量productsJSON

using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Newtonsoft.Json;
using System.Net.Http;

namespace MyShop
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ProductsPage : ContentPage
    {
        public ProductsPage(string title)
        {
            InitializeComponent();
            Title = title;

            string productsJSON = App.productsJSON;

            displayProducts(productsJSON);
        }
    ...

為此,我收到錯誤: CS0120: An object reference is required for the non-static field, method, or property 'App.productsJSON'

我很困惑,因為從在線解決方案中引用另一個 class 的屬性時,您只需調用 class 然后點,然后調用屬性名稱。 我不太明白object reference錯誤,當我將它轉換為像<string>App.productsJSON這樣的字符串時它不起作用

您需要引用App class 的實例才能訪問非靜態字段或屬性

var json = ((App)Application.Current).productsJSON;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM