C# - 如何发布列表

所以我有这段代码可以使用 c# 发布JSON data到我的REST API


try

    {

        tempquantityofmenu = entQuantity.Text;

        CustList custo = new CustList();


        CustomerOrder custo1 = new CustomerOrder()

           {

              menu_name = tempnameofmenu,

              menu_quantity = tempquantityofmenu,

              menu_code = tempcodeofmenu

            };


        custo.CUSTOMER_ORDER.Add(custo1);


        await Navigation.PushAsync(new OrdernowCategory());

       }

        catch(Exception ex)

        {

            DisplayAlert("error", ex.ToString(), "OK");

        }

然后我得到这个 System.NullReferenceExeption: Object Reference not set to an instance of an object


public class CustomerOrder

{

    public string menu_name { get; set; }

    public string menu_quantity { get; set; }

    public string menu_code { get; set; }

}


public class CustList

{

    public List<CustomerOrder> CUSTOMER_ORDER { get; set; }

}

我认为我的问题是当向CUSTOMER_ORDER内部添加项目时try catch不起作用


智慧大石
浏览 165回答 2
2回答

德玛西亚99

因为您没有为CUSTOMER_ORDER属性创建实例,所以CUSTOMER_ORDER是引用类型,null默认情况下具有值。如果你想解决它,你可以给CUSTOMER_ORDER一个这样的实例集合。CustList custo = new CustList() {&nbsp;&nbsp; &nbsp; &nbsp;CUSTOMER_ORDER = new List<CustomerOrder>()&nbsp;};

喵喔喔

你可以public class CustList{&nbsp; &nbsp; public List<CustomerOrder> CUSTOMER_ORDER { get; set; } = new List<CustomerOrder>();}或者public class CustList{&nbsp; &nbsp; public List<CustomerOrder> CUSTOMER_ORDER { get; set; }&nbsp;&nbsp; &nbsp; public CustList()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; CUSTOMER_ORDER = new List<CustomerOrder>();&nbsp; &nbsp; }}或者custo.CUSTOMER_ORDER = new List<CustomerOrder>();custo.CUSTOMER_ORDER.Add(custo1);为了这个世界上所有整洁的事物的爱,不要用大写和下划线命名你的变量/属性/或andything
打开App,查看更多内容
随时随地看视频慕课网APP