繁体   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