NullReferenceException试图访问位于类中的列表?

时间:2014-09-11 02:22:55

标签: c# nullreferenceexception

我正在尝试使用Steam API检索信息。我创建了类offerStuffitemsClassofferStuff包含public List<itemsClass> items { get; set; },但是,每当我尝试通过os.items.Add(item)访问此列表时,我的程序都会崩溃NullReferenceException 1}}。是否有一些我遗失的声明?如果是这样,我将如何声明它以便我可以无异常地访问它?

    public static List<offerStuff> pollOffers()
    {
        using (dynamic tradeOffers = WebAPI.GetInterface("IEconService", config.API_Key))
        {
            List<offerStuff> OfferList = new List<offerStuff>();
            offerStuff os = new offerStuff();
            KeyValue kvOffers = tradeOffers.GetTradeOffers(get_received_offers: 1);//, active_only: 1
            foreach (KeyValue kv in kvOffers["trade_offers_received"].Children)
            {
                os.tradeofferid = kv["tradeofferid"].AsInteger(); ;
                os.accountid_other = Convert.ToUInt64(kv["accountid_other"].AsInteger());
                os.message = kv["message"].AsString();
                os.trade_offer_state = kv["trade_offer_state"].AsInteger();
                foreach (KeyValue kv2 in kv["items_to_receive"].Children)
                {
                    itemsClass item = new itemsClass();
                    item.appid = (kv2["appid"].AsInteger());
                    item.assetid = kv2["assetid"].AsInteger();
                    item.classid = kv2["classid"].AsInteger();
                    item.instanceid = kv2["instanceid"].AsInteger();
                    item.amount = kv2["amount"].AsInteger();
                    item.missing = kv2["missing"].AsInteger();

                    os.items.Add(item);
                }
                os.is_our_offer = kv["is_our_offer"].AsBoolean();
                os.time_created = kv["time_created"].AsInteger();
                os.time_updated = kv["time_updated"].AsInteger();
                OfferList.Add(os);
            }
            return OfferList;
        }
    }
}


public class offerStuff
{
    public int tradeofferid { get; set; }
    public SteamID accountid_other { get; set; }
    public string message { get; set; }
    public int trade_offer_state { get; set; }
    public List<itemsClass> items { get; set; }
    public bool is_our_offer { get; set; }
    public int time_created { get; set; }
    public int time_updated { get; set; }
}
public class itemsClass
{
    public int appid { get; set; }
    public int assetid { get; set; }
    public int classid { get; set; }
    public int instanceid { get; set; }
    public int amount { get; set; }
    public int missing { get; set; }
}

1 个答案:

答案 0 :(得分:4)

问题可能是您没有初始化集合items。你可以在你的构造函数上这样做

public offerStuff() 
{
    items = new List<itemsClass>();
}