public App class 中的变量无法在其他 class xamarin 表单中引用

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 中,我想引用 public 变量 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 的 实例 才能访问 non-static 字段或 属性

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