我有這個作為我的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'
我很困惑,因為從在線解決方案中參考另一個類的屬性時,您只需呼叫類,然后呼叫點,然后呼叫屬性名稱。我不太明白這個object reference錯誤,當我將它轉換成字串時它不起作用<string>App.productsJSON
uj5u.com熱心網友回復:
您需要對類實體的參考App才能訪問非靜態欄位或屬性
var json = ((App)Application.Current).productsJSON;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473731.html
