简体   繁体   English

C#Xamarin如何在类中使用现有List?

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

I am struggling with a problem. 我正在为一个问题而苦苦挣扎。

In my MainActivity.cs I made a List like this: 在我的MainActivity.cs文件中,我做了一个这样的列表:

//Define
public List<products> mItems;

Here I created the List: 在这里,我创建了列表:

mItems = new List<products>();

And over here I fill the List: 在这里,我填写列表:

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);
}

Now I want to use this List in another class, so I use this code in the new class (Lets call it "Class2"): 现在,我想在另一个类中使用此List,因此在新类中使用此代码(将其称为“ Class2”):

public List<products> mItems;

But mItems is Null, what am I doing wrong. 但是mItems为Null,我在做什么错。

Again a little update with an Error of course. 再次更新当然有一个错误。

In the MainActivity, I made these changes: 在MainActivity中,我做了以下更改:

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

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

And in Class2: 在Class2中:

List<products> mItems = MainActivity.ProductList;

I don't know if I am doing the good way, but my error is: "An object reference is required for the non-static field, method, or property " 我不知道自己是否做得很好,但是我的错误是:“非静态字段,方法或属性需要对象引用”

I have no idea what I have to do! 我不知道该怎么办! Any suggestions? 有什么建议么?

In your Class2, you have to get it from your Class1, just gave to a second list the same name isn't enough. 在Class2中,您必须从Class1中获取它,仅给第二个列表使用相同的名称是不够的。

Here is an example and you should revise the object programming ( https://msdn.microsoft.com/en-us/library/dd460654(v=vs.120).aspx#Properties ) 这是一个示例,您应该修改对象编程( 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;
    }
}

This answer is too broad to answer definitively, but I shall try help. 这个答案范围太广,无法确切地回答,但我将尽力提供帮助。

Example 1 if you want to pass a list from your main activity to an instance of a class you are creating in the main activity you can pass the list when declaring a new instance of it. 示例1,如果要将列表从主活动传递到要在主活动中创建的类的实例,则可以在声明列表的新实例时传递该列表。

MyListClass listClass = new MyListClass(productList);

then in the class you have something like 然后在课堂上,你会喜欢

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

Example 2 If you are looking to pass the list from your main activity to lets say a fragment there are a number of ways to do so. 示例2如果您希望将主要活动中的列表传递给一个片段,则有多种方法可以执行此操作。 you can use the following. 您可以使用以下内容。

ListFragment listFragment = ListFragment.NewInstance(productList);

then in the fragment you have a static class NewInstance like so. 然后在片段中有一个静态类NewInstance,就像这样。

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

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

Example 3 You can use a listener that your mainActivity implements and through the listener call a method that will return a list to you, the reason you use a listener is to decouple your fragment from any activity, an example of this would be 示例3您可以使用mainActivity实现的侦听器,并通过该侦听器调用将向您返回列表的方法,您使用侦听器的原因是将片段与任何活动分离,例如:

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

then your IListFragmentListener.cs 然后你的IListFragmentListener.cs

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

finally in your fragment 终于在你的片段中

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();
    }
}

Activity to Activity Just a quick note on passing a List from one activity to another, as far as I know the cleanest way to do this is to make your list object serializable and serialize it in one activity and Deserialize it in the activity you wish to pass the list too. 从活动到活动只是将一个活动中的列表传递给另一个活动的快速提示,据我所知,最干净的方法是使列表对象可序列化,并在一个活动中将其序列化,然后在您想要的活动中反序列化也通过列表。 This can cause performance issues however 这可能会导致性能问题

如何使用清单<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# 扩展现有类 - Xamarin / C# extending an existing class 如何在类构造函数中使用方法数据 c# xamarin - How to use method data in a class constructor 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> - How to use List<object> in response to API - C# Xamarin 如何在C#/ Xamarin中使用“ .ScrollTo”列表视图方法 - How to use the “.ScrollTo” list view method in C#/Xamarin 如何在不使用类的现有C#程序中使用自定义类? - how do I use a custom class in an existing C# program that did not use a class? 如何在Xamarin C#中使用setCompoundDrawables - How to use setCompoundDrawables with Xamarin c# 如何在Xamarin C#for iOS中使用UIPageControl - How to use UIPageControl in Xamarin C# for iOS 如何在 C# (Xamarin) 中使用 setOnTouchListener? - How to use setOnTouchListener in C# (Xamarin)? C#如何使用列表类作为自定义窗体的属性 - C# How to use List Class as Property of Custom Form 如何以Xamarin形式在XAML文件中使用C#类 - How can I use my C# class in my XAML file in xamarin forms
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM