簡體   English   中英

C#Xamarin如何在類中使用現有List?

[英]C# Xamarin How to use a existing List in a class?

我正在為一個問題而苦苦掙扎。

在我的MainActivity.cs文件中,我做了一個這樣的列表:

//Define
public List<products> mItems;

在這里,我創建了列表:

mItems = new List<products>();

在這里,我填寫列表:

foreach (var property in Array)
{
    //Convert every value in Array to string
    var propertyList = JsonConvert.DeserializeObject<List<products>>(property.ToString());

    //Add all strings to List
    mItems.AddRange(propertyList);
}

現在,我想在另一個類中使用此List,因此在新類中使用此代碼(將其稱為“ Class2”):

public List<products> mItems;

但是mItems為Null,我在做什么錯。

再次更新當然有一個錯誤。

在MainActivity中,我做了以下更改:

private List<products> mItems = new List<products>();

public List<products> ProductList
{
    get { return mItems; }
}

在Class2中:

List<products> mItems = MainActivity.ProductList;

我不知道自己是否做得很好,但是我的錯誤是:“非靜態字段,方法或屬性需要對象引用”

我不知道該怎么辦! 有什么建議么?

在Class2中,您必須從Class1中獲取它,僅給第二個列表使用相同的名稱是不夠的。

這是一個示例,您應該修改對象編程( https://msdn.microsoft.com/zh-cn/library/dd460654(v=vs.120).aspx#Properties

public class Class1 {
    public List<products> mItems;

    public Class1() {

        //Startup WebClient
        WebClient client = new WebClient();

        //Define URL to download
        string link = @"http://websitelink.todownload.json.php";

        //Download json website content
        string json = new WebClient().DownloadString(link);

        //Parse json content
        var jObject = JObject.Parse(json);

        //Create Array from everything inside Node:"Products"
        var productPropery = jObject["Products"] as JArray;

        mItems = new List<products>();

        foreach (var property in Array)
        {
            //Convert every value in Array to string
            var propertyList = JsonConvert.DeserializeObject<List<products>>(property.ToString());

            //Add all strings to List
            mItems.AddRange(propertyList);
        }
    }
}

public class Class2 {
    public List<products> mItems;

    public Class2() {
        var class1Instance = new Class1();
        mItems = class1Instance. mItems;
    }
}

這個答案范圍太廣,無法確切地回答,但我將盡力提供幫助。

示例1,如果要將列表從主活動傳遞到要在主活動中創建的類的實例,則可以在聲明列表的新實例時傳遞該列表。

MyListClass listClass = new MyListClass(productList);

然后在課堂上,你會喜歡

public class MyListClass
{
    private List<Products> _productList;
    public MyListClass(List<Products> productList)
    {
        _products = productList
    }
}

示例2如果您希望將主要活動中的列表傳遞給一個片段,則有多種方法可以執行此操作。 您可以使用以下內容。

ListFragment listFragment = ListFragment.NewInstance(productList);

然后在片段中有一個靜態類NewInstance,就像這樣。

public class ListFragment :Fragment
{
    private List<Products> _productList;

    public static ListFragment NewInstance(List<Products> productList)
    {
        _productList = productList;
        ListFragment fragment = new ListFragment();
        return fragment;
    }
}

示例3您可以使用mainActivity實現的偵聽器,並通過該偵聽器調用將向您返回列表的方法,您使用偵聽器的原因是將片段與任何活動分離,例如:

public class MainActivity : IListFragmentListener
{
//implement the interface below
    public List<Products> GetProductsList()
    {
        return productsList;
    }
}

然后你的IListFragmentListener.cs

public interface IListFragmentListener
{
    List<Products> GetProductsList();
}

終於在你的片段中

public class ListFragment :Fragment
{
    private List<Products> _productList;
    private IListFragmentListener _listener;
    public override void OnAttach(Context context)
    {
        base.OnAttach(context);
        _listener = (IAddDateFragmentListner)context;
    }
    private void RandomFragmentMethod()
    {
        _productList = _listener.GetProductsList();
    }
}

從活動到活動只是將一個活動中的列表傳遞給另一個活動的快速提示,據我所知,最干凈的方法是使列表對象可序列化,並在一個活動中將其序列化,然后在您想要的活動中反序列化也通過列表。 這可能會導致性能問題

如何使用清單<object>回應 API - C# Xamarin<div id="text_translate"><p> I trying to convert this JSON API ( <a href="http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8" rel="nofollow noreferrer">http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8</a> ) to C# object here: <a href="https://json2csharp.com/" rel="nofollow noreferrer">https://json2csharp.com/</a></p><p> 我收到List<object> aladinModel { get; set; } List<object> aladinModel { get; set; }</p><p> 如何在我對 API 的回復中使用此列表 aladinModel:</p><pre> public async Task List<AladinModel> GetWeatherData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<AladinModel>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 此行不正確:</p><pre> public async Task List<AladinModel> GetWeatherData(string query)</pre><p> 如何在這里使用這個列表?</p><p> ================================================ =============</p><p> <strong>更新</strong></p><p> ================================================ =============</p><p> object class 看起來像:</p><pre> class ItemsAPI { public partial class RootAladinModel { [JsonProperty("aladinModel")] public AladinModel[] AladinModel { get; set; } } public partial class AladinModel { [JsonProperty("DATS")] public DateTimeOffset Dats { get; set; } [JsonProperty("TA")] public double Ta { get; set; } [JsonProperty("RH")] public double Rh { get; set; } [JsonProperty("WS")] public double Ws { get; set; } [JsonProperty("RR")] public double Rr { get; set; } [JsonProperty("SR")] public double Sr { get; set; } [JsonProperty("APRES")] public double Apres { get; set; } } }</pre><p> RestService class 看起來像:</p><pre> public async Task<List<AladinModel>> GetAladinData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<List<AladinModel>>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 但我收到錯誤:</p><pre> {Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[pizhevsoft.Models.ItemsAPI+AladinModel]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'aladinModel', line 1, position 15. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x003a0] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0006d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at pizhevsoft.Services.RestServiceAPI.GetAladinData (System.String query) [0x00151] in C:\Users\Admin\Desktop\pizhevsoft\pizhevsoft\pizhevsoft\pizhevsoft\Services\RestServiceAPI.cs:30 }</pre></div></object>

[英]How to use List<object> in response to API - C# Xamarin

暫無
暫無

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

相關問題 Xamarin/C# 擴展現有類 如何在類構造函數中使用方法數據 c# xamarin 如何使用清單<object>回應 API - C# Xamarin<div id="text_translate"><p> I trying to convert this JSON API ( <a href="http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8" rel="nofollow noreferrer">http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8</a> ) to C# object here: <a href="https://json2csharp.com/" rel="nofollow noreferrer">https://json2csharp.com/</a></p><p> 我收到List<object> aladinModel { get; set; } List<object> aladinModel { get; set; }</p><p> 如何在我對 API 的回復中使用此列表 aladinModel:</p><pre> public async Task List<AladinModel> GetWeatherData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<AladinModel>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 此行不正確:</p><pre> public async Task List<AladinModel> GetWeatherData(string query)</pre><p> 如何在這里使用這個列表?</p><p> ================================================ =============</p><p> <strong>更新</strong></p><p> ================================================ =============</p><p> object class 看起來像:</p><pre> class ItemsAPI { public partial class RootAladinModel { [JsonProperty("aladinModel")] public AladinModel[] AladinModel { get; set; } } public partial class AladinModel { [JsonProperty("DATS")] public DateTimeOffset Dats { get; set; } [JsonProperty("TA")] public double Ta { get; set; } [JsonProperty("RH")] public double Rh { get; set; } [JsonProperty("WS")] public double Ws { get; set; } [JsonProperty("RR")] public double Rr { get; set; } [JsonProperty("SR")] public double Sr { get; set; } [JsonProperty("APRES")] public double Apres { get; set; } } }</pre><p> RestService class 看起來像:</p><pre> public async Task<List<AladinModel>> GetAladinData(string query) { List<AladinModel> weatherData = new List<AladinModel>(); try { var response = await _client.GetAsync(query); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = JsonConvert.DeserializeObject<List<AladinModel>>(content); } } catch (Exception ex) { Debug.WriteLine("\t\tERROR {0}", ex.Message); } return weatherData; }</pre><p> 但我收到錯誤:</p><pre> {Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[pizhevsoft.Models.ItemsAPI+AladinModel]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'aladinModel', line 1, position 15. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x003a0] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0006d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 at pizhevsoft.Services.RestServiceAPI.GetAladinData (System.String query) [0x00151] in C:\Users\Admin\Desktop\pizhevsoft\pizhevsoft\pizhevsoft\pizhevsoft\Services\RestServiceAPI.cs:30 }</pre></div></object> 如何在C#/ Xamarin中使用“ .ScrollTo”列表視圖方法 如何在不使用類的現有C#程序中使用自定義類? 如何在Xamarin C#中使用setCompoundDrawables 如何在Xamarin C#for iOS中使用UIPageControl 如何在 C# (Xamarin) 中使用 setOnTouchListener? C#如何使用列表類作為自定義窗體的屬性 如何以Xamarin形式在XAML文件中使用C#類
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM