C# 为c类中的项目列表添加值#
下面是我的三种方法C# 为c类中的项目列表添加值#,c#,asp.net-mvc,c#-4.0,C#,Asp.net Mvc,C# 4.0,下面是我的三种方法 public class abcOrder { public Items items { get; set; } } public class Item { public string orderrefno { get; set; } public string sku { get; set; } public string qty { get; set; } } public class Items {
public class abcOrder
{
public Items items { get; set; }
}
public class Item
{
public string orderrefno { get; set; }
public string sku { get; set; }
public string qty { get; set; }
}
public class Items
{
public List<Item> item { get; set; }
}
但是我在abcOrder.items中得到的条目为空。请帮助。首先,我不明白为什么您有
items
类。为什么不让abcOrder
类有一个List属性呢
但你的问题是你从来没有初始化过你的对象。如果从未实际创建过对象,则无法使用该对象。最简单的方法是在类构造函数中,如下所示
public class abcOrder
{
public abcOrder()
{
items = new Items();
}
public Items items { get; set; }
}
public class Items
{
public Items()
{
item = new List<Item>();
}
public List<Item> item { get; set; }
}
公共类记录器
{
公共录音机
{
项目=新项目();
}
公共项目{get;set;}
}
公共类项目
{
公共物品()
{
item=新列表();
}
公共列表项{get;set;}
}
谢谢。我正在使用json序列化程序。要以正确的格式创建json,我需要Items类。非常感谢您没有初始化您的列表项
!
public class abcOrder
{
public abcOrder()
{
items = new Items();
}
public Items items { get; set; }
}
public class Items
{
public Items()
{
item = new List<Item>();
}
public List<Item> item { get; set; }
}